Java:Socket关闭连接和ObjectInputStream
我的代码看起来像这样,这是服务器代码(Runnable
)
public void run() {
while (true) {
try {
System.out.println("Waiting for client...");
this.socket = serverSocket.accept();
System.out.println("Client accepted");
while (true) {
readCommand();
try {
Thread.sleep(2);
} catch (Exception e) {
}
}
} catch (Exception ex) {
Main.error("Server stopped for current host", ex);
}
}
}
我的问题是:当客户端关闭连接时,他仍在等待读取readCommand();
中的命令直到发送命令并抛出EOFException
。这是我的 readCommand 方法:
private void readCommand() throws Exception {
Object o = new ObjectInputStream(socket.getInputStream()).readObject();
if (o instanceof Command) {
((Command) o).execute();
return;
}
if (o instanceof Recorder) {
System.out.println("Recording received");
((Recorder) o).executeRecord();
return;
}
if (o instanceof MyKeyEvent) {
((MyKeyEvent) o).execute();
return;
}
}
所以我认为在读取之前必须检查连接是否打开。
编辑:如果我评估run
方法代码,EOFException
将在try-catch-body
中抛出。但他停止接受客户。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果客户端关闭连接,
EOFException
正是我所期望的。所以我不太确定您的问题实际上是什么。。也许您需要区分预期的客户端断开连接和意外的客户端断开连接。在这种情况下,您也许应该发送某种End-of-message
对象来标记传输结束?如果您想检查信息是否可用,可以使用 available() 方法。顺便说一句,我认为您不需要
Thread.sleep(2)
,因为我希望在没有数据的情况下对 valid 输入流的读取会挂起。An
EOFException
is exactly what I'd expect if the client closes the connection. So I'm not quite sure what your problem actually is. Perhaps you need to distinguish between an expected client disconnect and an unexpected client disconnect. In which case you should perhaps send some sort ofEnd-of-message
object to mark the end of transmission ?If you want to check if info is available, there's an available() method on the stream. I don't think you need your
Thread.sleep(2)
, btw, since I would expect a read on a valid input stream to hang in the absence of data.您还可以“仅”添加另一个 try-catch 来捕获 EOFException
当然,命令结束更加智能/优雅......
[]]
You can also "just" add another try-catch to catch just the EOFException
sure, the End-of-command is much smarter/elegant...
[]]