Elias Schramm
Elias Schramm

Reputation: 15

How to catch a socket-timeout in Java

I'm writing a server with Java.net. Now i want to change some variables on socket-timeout.

I cant find a 'onTimeout' interface or something similar.

Now I'm searching for a solution for this problem.

Upvotes: 1

Views: 159

Answers (1)

Avi
Avi

Reputation: 2641

You say you're using java.net so I'm assuming that you're using something like a java.net.ServerSocket. If you call setSoTimeout on your instance of ServerSocket, you will be able to set a timeout for your socket. Then, when you block during calls to accept, your ServerSocket will keep track of the timeout. As you can see in the documentation, accept throws a SocketTimeoutException if a timeout has been defined and the wait time has exceeded the timeout. So, you'll end up with something like this (forgive me for being a bit rusty on Sockets):

try(ServerSocket ssock = new ServerSocket(...))
{
    ssock.setSoTimeout(10_000); // 10 second timeout
    while(true)
    {
        Socket csock = ssock.accept();
        methodToStartThreadThatHandlesClientSocket(csock);
    }
}
catch(SocketTimeoutException ste)
{
    //handle socket timeout
}
catch(Exception other)
{
    //handle other exceptions
}

Upvotes: 1

Related Questions