user555641
user555641

Reputation: 11

SocketTimeoutException: Accept timed out

The following bit of code throws java.net.SocketTimeoutException: Accept timed out:

ServerSocket serverSocket = new ServerSocket(0, 1, InetAddress.getLocalHost());
serverSocket.setSoTimeout(6000);  
serverSocket.accept();

I have tried changing everything I can in creating a ServerSocket but the error remains the same. Please guide me in what I'm missing here, if anything.

Upvotes: 1

Views: 24856

Answers (1)

Stephen C
Stephen C

Reputation: 719551

What your code is doing is listening for 6 seconds for incoming TCP/IP requests on port zero for the local host1.

Here are some reasons why you might get a SocketTimeoutException.

  • Nothing tries to connect to your service within the 6 second timeframe.
  • Something tries to connect, but it is trying to connect on the wrong port. (Port zero sounds to me like you are trying to accept requests on "any" port, and I think that is unlikely to work.)
  • There is a software or hardware firewall (or packet filter) that is preventing connection requests from reaching your application, or is blocking the replies.

1 - If you don't want that "only accept an exception if it arrives within 6 seconds" behaviour ... which strikes me as a bit odd ... you shouldn't set a timeout on the server socket object.

Upvotes: 4

Related Questions