Mám teoretickou otázku, lze v Androidím equipmentu na trvalo otevřít Socket komunikaci?
Používám tento kód, který ale díky volaní AsyncTask vždy tu komunikaci uzavře. Jednu instance AsyncTask lze volat pouze jednou.
public String activateSocket(final byte[] data) throws IOException {
if (socketIsFree) {
socketIsFree = false;
try {
socket = new Socket();
Log.i("SOCKET", "Start");
socket.setSoTimeout(TIMEOUT);
InetSocketAddress ins = new InetSocketAddress(BASEURL, PORT);
Log.i("SOCKET", ins.toString());
socket.connect(ins, 1000);// TIMEOUT);
Log.i("SOCKET", String.format("TimeOut %dms %s", socket.getSoTimeout(), socket.getLocalAddress().toString()));
socket.setKeepAlive(false);
socket.setSendBufferSize(SENDBUFFSIZE);
socket.setReceiveBufferSize(RECBUFFSIZE);
StringBuilder sb = new StringBuilder();
final InputStream is = socket.getInputStream();
final BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String tx = "";
try {
//Log.i("SOCKET",s);
final OutputStream os = socket.getOutputStream();
os.write(data);
os.flush();
Log.i("SOCKET", "Start receiving");
long ms = System.currentTimeMillis();
char[] chb = null;
while (true) {
new Thread().sleep(10);
int aval = is.available();
Log.i("SOCKET", String.valueOf(aval));
if (aval > 0) {
// prvni 4 byte oznacuji delku paketu je to litle endian
byte []b=new byte[4];
is.read(b,0,4);
delkaPaketu= ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getInt();
chb = new char[delkaPaketu];
precteno+= br.read(chb, 0, delkaPaketu);
sb.append(chb);
if (precteno==delkaPaketu) {
sb.trimToSize();
tx = sb.toString();
break;
}
}
if (System.currentTimeMillis() - ms > TIMEOUT * 2) {
throw new SocketTimeoutException();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//StopSocket();
}
Log.i("SOCKET", "Received data: " + tx);
Log.i("SOCKET", "End receiving");
return tx;
} catch (SocketTimeoutException ste) {
Log.i("SOCKET", "TimeOut");
ste.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
//StopSocket();
}
socketIsFree = true;
}
return null;
}
Diky za každou myšlenku