I'm learning about Java Socket programming by creating a multiplayer card game application. The client will handle both the game and a little chat window.
My client reads in instructions from the server from a loop like so:
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
if (line.startsWith("SOME_COMMAND") {
// get necessary input from user
} else if (line.startsWith("MESSAGE") {
// tell EDT to update chat window
}
}
My problem, though, is that getting input from the user pauses the loop, which stops the chat window from updating.
Is there a 'best practice' for this kind of problem? I was thinking something along the lines of a filter, running in a separate thread, that processes messages and feeds non-messages back into a new stream that the main thread will loop through.
readLine()for null before doing anything else, and stop looping when you get it. The usual way of writing the loop iswhile ((line = in.readLine()) != null) ....