0

I'm trying to implement a server that accepts connections but times out and closes that specific connection only if it hasn't received anything from that connection after N milliseconds.

From my possible misunderstanding of ServerSocket's setSoTimeout(int milliseconds) method, I thought this behaviour could be accomplished by passing N to setSoTimeout.

What I'm experiencing is once a client makes a connection, and doesn't send anything over that connection for N seconds, the server catches a SocketTimeoutException, but then completely stops execution and ends the process running the server program. Here is my server's listen method:

    private static void listen() throws IOException {
    while(true) {
        try {
            Socket clientSocket = serverSocket.accept();
            Connection connexion = new Connection(clientSocket);
            connexion.start();  
        } catch (SocketTimeoutException e) {
            System.out.println("Socket timed out!");
            break;
        }           
    } 
}

I successfully catch the SocketTimeoutException, ignore it (bad I know!) and assume that the client connection that caused the exception gets closed. Then I just break out of the catch block to continue accepting other client connections. What am I missing here?

2 Answers 2

0

You need to add continue; instead of break; in the try-catch clause. The server will keep listening.

0

assume that the client connection that caused the exception gets closed.

Incorrect assumption. The accept() is what has timed out. The client connection hasn't done anything yet.

Then I just break out of the catch block to continue accepting other client connections.

Err, no, you break out of the catch block to stop accepting other client connections. You're breaking out of the accept loop.

What am I missing here?

A continue instead of a break.

If you don't care about the SocketTimeoutException why are you setting a socket timeout on the ServerSocket? Just remove that.

3
  • Is there a way I can set a timeout on the client Socket then? Is there a method on the Socket class that would allow me to achieve my desired functionality?
    – cbrad
    Oct 30, 2014 at 7:59
  • Yes, err, setSoTimeout(), the same one you called on the ServerSocket. Did you even look?
    – user207421
    Oct 30, 2014 at 20:34
  • My bad, I must have missed seeing Socket's setSoTimeout method; I thought it was only available for ServerSocket. Thanks again for your informative answer @EJP
    – cbrad
    Oct 30, 2014 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.