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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…