I am trying to make a simple chat server/client application. My server is made in python, using twisted. Everything works good with it, tested it with telnet.
Basically the server sends to all it's clients every message it's getting. I need a way to read forever from the socket, so that I can get all messages. I don't think it's the best approach, but I tried to make it using a thread, that reads forever (for now). After the client is connected to the server, it will start a thread, that will check forever for updates.
Here is my CheckUpdates class that implements Runnable:
class CheckUpdates implements Runnable{
@Override
public void run() {
Log.d("ME", "CHECKING FOR UPDATES");
while(true)
{
// reader.lines().forEach(System.out.println);
String line;
Log.d("ME","IN WHILE");
try {
while ((line = reader.readLine()) != null) {
Log.d("ME", "READING LINE");
Looper.prepare();
Toast.makeText(MainActivity.this, line, Toast.LENGTH_SHORT).show();
Looper.loop();
}
} catch (IOException e) {
Log.d("ME", "EXCEPTION IN WHILE: " + e.getMessage().toString());
}
Log.d("ME", "END OF WHILE CHECK UPDATES");
}
}
}
I am starting the thread right after I'm connected to the server. Basically, I am getting the first message (first toast), and right after that, nothing more comes in, not even the END OF WHILE CHECK UPDATES logcat message.
Could it get stuck forever in the while that checks for a new line from socket ? Also, if there is a more elegant way of doing this, would really appreciate if somebody could point me in the right direction.
Could it get stuck forever in the while that checks for a new line from socket?
Yes, if there's no more data. But I suspect that's not the problem. I suspect the problem is this:
Looper.loop();
As far as I can see, you don't need to use Looper
at all here. Assuming you're really on a dedicated thread, what messages do you expect to process? With nothing calling Looper.quit()
, the Looper.loop()
call will block forever, I suspect.
Just get rid of the two Looper
calls and I suspect you'll be able to see all the messages.
EDIT: However, you'll need to show the toast on the UI thread - see this SO question for details of that, using Activity.runOnUiThread
. I'm not sure that showing a toast on every message is an ideal UI, mind you...
You'll also want to get rid of the while (true)
- you're already looping on the inner loop, so that's fine.