【发布时间】:2013-08-10 09:33:14
【问题描述】:
我正在使用 Sockets api 在 Java 中创建网络游戏,但遇到以下问题:
当应用启动时,服务器套接字开始侦听并为每个新客户端生成一个新线程(基本的东西,不需要显示此代码)。
然后客户端开始对话,发送字符串“LOGIN”。服务器接收它并以“LOGIN_OK”响应。现在对话结束了,但控制台继续打印 LOGIN_OK(发生在客户端)。
为什么会这样? readLine() 不应该阻塞吗? 感谢您的澄清!
编辑:问题出在客户端循环中。客户端正在将服务器的响应发送回服务器!刚刚注释掉那行就解决了!
服务器循环
public void run()
{
String fromClient = null;
try {
while ((fromClient = in.readLine()) != null) {
System.out.println(fromClient);
String response = SessionProtocol.handleInput(fromClient);
out.println(response);
Thread.sleep(50L);
}
} catch(IOException ex){ex.printStackTrace();}
catch(InterruptedException ex){ex.printStackTrace();}
}
客户端循环
public void run()
{
String fromServer = null;
try {
while ((fromServer = in.readLine()) != null) {
System.out.println(fromServer);
String response = SessionProtocol.handleInput(fromServer);
// next line causes the problem
//out.println(response);
Thread.sleep(50L);
}
} catch(IOException ex){ex.printStackTrace();}
catch(InterruptedException ex){ex.printStackTrace();}
}
【问题讨论】:
-
只是一个建议,看看 ZeroMQ,一个 Java 套接字库;它更适合您正在做的事情,而不是使用普通的 Java 套接字:github.com/zeromq/jeromq
-
谢谢,我一定会检查的!
标签: java sockets bufferedreader