0

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

4

2 回答 2

3

如果客户端关闭连接, AnEOFException正是我所期望的。所以我不太确定你的问题到底什么。也许您需要区分预期的客户端断开连接和意外的客户端断开连接。在这种情况下,您也许应该发送某种End-of-message对象来标记传输结束?

如果你想检查信息是否可用,流上有一个available()方法。我不认为你需要你的Thread.sleep(2),顺便说一句,因为我希望在没有数据的情况下对有效输入流的读取会挂起。

于 2009-10-12T18:44:33.313 回答
0

您还可以“仅”添加另一个 try-catch 来仅捕获 EOFException

public void run() {
    while (true) {
        try {
            System.out.println("Waiting for client...");
            this.socket = serverSocket.accept();
            System.out.println("Client accepted");
            try {
                while (true) {
                    readCommand();
                    try {
                        Thread.sleep(2);
                    } catch (Exception e) {
                    }
                }
            } catch (EOFException ex) {
                System.out.println("client closed");
            }
        } catch (Exception ex) {
            Main.error("Server stopped for current host", ex);
        }
    }
}

当然,命令结束更聪明/优雅...
[]]

于 2009-10-12T19:45:41.990 回答