如何使用socket.setSoTimeout()?

时间:2015-04-24 13:24:39

标签: java sockets

当您使用socket.seSoTimeout(5000);在套接字上设置超时时,套接字是关闭还是在超时后停止侦听?我是否必须再次打开套接字才能继续收听或自动打开?

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?

2 个答案:

答案 0 :(得分:2)

您可以在while (true)中包含try / catch来测试您的问题。简短的回答是否定的,您不必重新打开套接字。 setSoTimeout()只是告诉套接字在您尝试执行其他任何操作之前等待这么长时间。

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");
    }
}

结果(您可以看到套接字在超时后仍可重用):

enter image description here

答案 1 :(得分:0)

正如documentation所述:

  

如果超时到期,则引发java.net.SocketTimeoutException,尽管ServerSocket仍然有效

所以不,它不会关闭套接字。下次您想知道某些工作原理时,请查看文档