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?
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):
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