问题描述
当您使用 socket.seSoTimeout(5000)设置套接字超时时,
套接字是否关闭或者在超时后停止监听?我是否必须再次打开套接字才能继续收听或自动打开?
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?
推荐答案
您可以通过包装try / catch来测试您的问题在中,而(true)
。简短的回答是否定的,你不必重新打开套接字。 setSoTimeout()
只是告诉套接字在你尝试做其他事情之前等待这么长时间。
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):
这篇关于如何使用socket.setSoTimeout()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!