What's The Best Way For An Android App To Listen For Incomming Tcp/ip Messages?
I want to write an app that will listen for alarm messages whenever it is in the range of a server (on the same WiFi network). What is the best way to do this? Should I simply wri
Solution 1:
I had same problem... I wanted to use comet but I havent much time to research about it..
you can see some sample here.. http://blogs.webtide.com/dyu/entry/android_chat_using_jetty_cometd
and I choosed infinite loops for communication
here is my code..
publicclassServerActivityextendsActivity {
private TextView serverStatus;
// default ippublicstaticStringSERVERIP="10.0.2.15";
// designate a portpublicstaticfinalintSERVERPORT=12345;
privateHandlerhandler=newHandler();
private ServerSocket serverSocket;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Threadfst=newThread(newServerThread());
fst.start();
}
publicclassServerThreadimplementsRunnable {
Stringline="";
publicvoidrun() {
try {
if (SERVERIP != null) {
handler.post(newRunnable() {
@Overridepublicvoidrun() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = newServerSocket(SERVERPORT);
while (true) {
// listen for incoming clientsSocketclient= serverSocket.accept();
handler.post(newRunnable() {
@Overridepublicvoidrun() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReaderin=newBufferedReader(newInputStreamReader(client.getInputStream()));
// byte[] resultBuff = new byte[0];// byte[] buff = new byte[1024];// int k = -1;// while((k = client.getInputStream().read(buff, 0, buff.length)) > -1) {// byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read// System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes//System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy current lot//resultBuff = tbuff; // call the temp buffer as your result buff//}//System.out.println(resultBuff.length + " bytes read.");while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(newRunnable() {
@Overridepublicvoidrun() {
serverStatus.setText(line);
}
});
}
break;
} catch (Exception e) {
handler.post(newRunnable() {
@Overridepublicvoidrun() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(newRunnable() {
@Overridepublicvoidrun() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(newRunnable() {
@Overridepublicvoidrun() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
Post a Comment for "What's The Best Way For An Android App To Listen For Incomming Tcp/ip Messages?"