user3657834
user3657834

Reputation: 259

how to use socket.setSoTimeout()?

When you set a timeout on a socket with socket.seSoTimeout(5000); does the socket close or just stop listening after it times out? Will I have to open the socket again to continue listening or will it open automatically?

receivingSocket.setSoTimeout(5000); // set timer
try{
  receivingSocket.receive(packet);
}
catch(SocketTimeoutException e){
  System.out.println("### Timed out after 5 seconds.");
}
//will I have to reopen the socket here?

Upvotes: 2

Views: 8942

Answers (2)

Vince
Vince

Reputation: 15146

As the documentation states:

If the timeout expires, a java.net.SocketTimeoutException is raised, though the ServerSocket is still valid

So no, it will not close the socket. Next time you're wondering how something works, check out the documentation

Upvotes: 0

Shar1er80
Shar1er80

Reputation: 9041

You can test your question by wrapping your try/catch in a while (true). The short answer is no, you do not have to reopen the socket. The setSoTimeout() is just telling the socket to wait this long for data before you try to do anything else.

byte[] buffer = new byte[1000];
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
DatagramSocket receiveSocket = new DatagramSocket(5505, InetAddress.getByName("127.0.0.1"));
receiveSocket.setSoTimeout(5000);
while (true) {
    try {
        receiveSocket.receive(p);
    } catch (SocketTimeoutException ste) {
        System.out.println("### Timed out after 5 seconds");
    }
}

Results (You can see that the socket is still reusable after it timesout):

enter image description here

Upvotes: 2

Related Questions