Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 thread, it always came across an error socket closed because in the inner class thread i called the receive() method,and it blocked the inner class thread. here is the code of the inner class:

class ReceiveText extends Thread
{
    @Override
    public void run()
    {
        while(true)
        {
            byte[] buffer = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            try {
                udpSocket.receive(dp);//blocked here
                byte[] data = dp.getData();
                String message = new String(data, 0 , dp.getLength());
                setTxtAreaShowMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

i want to stop the inner class thread before close the DatagramSocket, but the stop() method is not recommended. how can i do that?

like image 483
cloud Avatar asked Nov 01 '11 03:11

cloud


2 Answers

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)

like image 150
prunge Avatar answered Oct 12 '22 11:10

prunge


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

like image 40
Cheng Avatar answered Oct 12 '22 11:10

Cheng