Server side socket close detection

时间:2015-09-14 15:31:15

标签: java sockets outputstream

I want to detect a server-sided socket close (closed by socket.setSoTimeout) by sending data from the client Socket OutputStream (socket.getOutputStream().write(42)). If the Socket is closed on the server-side this should cause an Exception. But it only throws an Exception if I send data twice:

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;
    }
}

How can you explain this behaviour?

1 个答案:

答案 0 :(得分:0)

K这里有解释:

您正在将第一个字节发送到服务器。服务器获取它,然后关闭套接字。然后,在THE NEXT WRITE上,由于套接字连接已关闭,因此会收到IOException。