我的代码如下所示,这是服务器代码 ( 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
-method 代码,EOFException
则会在try-catch-body
. 但他停止接受客户。