简体   繁体   English

尽管阻塞了代码,如何继续从Java套接字的输入流中读取?

[英]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. 我正在通过创建一个多人纸牌游戏应用程序来学习Java Socket编程。 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. 不要在EDT中执行非UI的工作。 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 . 让非EDT线程使用SwingUtilities.invokeLaterSwingUtilities.invokeAndWait通知更新是否有EDT。 This is probably the best way to go for socket-polling. 这可能是进行套接字轮询的最佳方法。
  2. Launch the non-EDT activity using SwingWorker . 使用SwingWorker启动非EDT活动。 I personally consider SwingWorker to only be appropriate in response to some action by the user. 我个人认为SwingWorker仅适合于响应用户的某些操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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