0

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 Answers1

0

K here's the explanation:

You're sending the first byte to the server. Server gets it, and then closes the socket. Then, on THE NEXT WRITE, you get an IOException, since the socket connection is closed.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • So after the SO TIMEOUT the server doesn't close the connection itself? – Basti Destruction Sep 14 '15 at 18:38
  • 1
    @qwertz1029384756 I don't know how to answer that question, as you haven't posted the server code. Normally, on SO TIMEOUT, the socket would close. And normally, if you had a listener on the client side blocked listening on that connection (ie InputStream.read()) that thread would wake up with a SocketException saying the socket was closed. But you don't appear to be listening for response back in your client code. So the next time you'd see the socket being closed is when you try to write to it – ControlAltDel Sep 14 '15 at 19:23