简体   繁体   中英

How to continuously read from a Java socket's inputstream despite blocking code?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM