服务器端套接字关闭检测



我想通过从客户端socket OutputStream (socket.getOutputStream().write(42))发送数据来检测服务器端socket关闭(由socket.setSoTimeout关闭)。如果套接字在服务器端关闭,则会导致异常。但它只抛出一个异常,如果我发送数据两次:

private boolean sendTest() {
    try {
        System.out.print("connection...");
        socket.getOutputStream().write(42); //Sending "*"
        socket.getOutputStream().write(42); //not working without this line
        System.out.println("ok");
        return true;
    } catch (IOException e) {
        System.out.println("error...disconnecting socket");
        disconnect();
        return false;
    }
}

你怎么解释这种行为?

解释如下:

你正在发送第一个字节到服务器。服务器获取它,然后关闭套接字。然后,在下一次写,你得到一个IOException,因为套接字连接是关闭的。

最新更新