how to use socket.setSoTimeout()?

2020-06-29 01:32发布

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?

标签: java sockets
2条回答
我只想做你的唯一
2楼-- · 2020-06-29 02:11

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

查看更多
混吃等死
3楼-- · 2020-06-29 02:20

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

查看更多
登录 后发表回答