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. ThesetSoTimeout()
is just telling the socket to wait this long for data before you try to do anything else.Results (You can see that the socket is still reusable after it timesout):
As the documentation states:
So no, it will not close the socket. Next time you're wondering how something works, check out the documentation