0

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.

1
  • You need to test the result of readLine() for null before doing anything else, and stop looping when you get it. The usual way of writing the loop is while ((line = in.readLine()) != null) .... Commented Jan 13, 2015 at 5:17

1 Answer 1

1

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:

  1. Have the non-EDT thread notify the EDT of updates, when they come in, using either SwingUtilities.invokeLater or SwingUtilities.invokeAndWait. This is probably the best way to go for socket-polling.
  2. Launch the non-EDT activity using SwingWorker. I personally consider SwingWorker to only be appropriate in response to some action by the user.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.