how can i stop the block method DatagramSocket.receive() in a thread

后端 未结 3 1618
情书的邮戳
情书的邮戳 2020-12-11 02:47

i create a DatagramSocket in the main thread,and then create a inner class thread to listen the port. when i close the DatagramSocket in the main t

相关标签:
3条回答
  • 2020-12-11 03:04

    Close the socket, which will stop the receive() call from blocking. If you first set a closed flag then in the catch (IOException) block you can safely ignore the exception if the flag is set. (You could probably also use isClosed() method on DatagramSocket instead of a flag)

    0 讨论(0)
  • 2020-12-11 03:13

    Socket.close() does the trick. Or you can use socket.setSoTimeout(1000); the setSoTimeout() method allows you to define a timeout period in milliseconds. For example:

    //if the socket does not receive anything in 1 second, 
    //it will timeout and throw a SocketTimeoutException
    //you can catch the exception if you need to log, or you can ignore it
    socket.setSoTimeout(1000); 
    socket.receive();
    

    Here is the javadoc for setSoTimeout();

    By default, the timeout is 0 which is indefinite, by changing it to a positive number, it will only block for the amount you specified. (Make sure you set it before calling socket.receive())

    Here is an example answered on this site: set timeout for socket receive

    0 讨论(0)
  • 2020-12-11 03:26

    With UDP, you could send the socket a datagram from another thread, so unblocking the read(). The datagran could, (depending on your protocol), contain a 'suicide' command or you could use an additional 'shutdown' boolean that the thread reads after read() returns.

    0 讨论(0)
提交回复
热议问题