Reputation: 61
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.
Upvotes: 0
Views: 1503
Reputation: 223183
Do not do non-UI work in the EDT. Always do stuff like reading from sockets, etc., from a separate thread. There are two ways to do this:
SwingUtilities.invokeLater
or SwingUtilities.invokeAndWait
. This is probably the best way to go for socket-polling.SwingWorker
. I personally consider SwingWorker
to only be appropriate in response to some action by the user.Upvotes: 1