Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...