I have the following block of code:
public void startListening() throws Exception {
serverSocket = new DatagramSocket(port);
new Thread() {
@Override
public void run() {
System.out.print("Started Listening");
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while (!stopFlag) {
try {
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData());
System.out.println("RECEIVED: " + message);
} catch (Exception ex) {
System.out.print("Execption :" + ex.getMessage());
}
}
}
}.start();
}
public void stopListening() {
this.stopFlag = true;
}
Suppose I set stopFlag to true. serverSocket.receive(receivePacket);
will wait until it receives a packet. What should I do if I want the thread to exit as soon as stopFlag is set to true.
I had the same problem with a socket as well and interrupt() didn't work. My problem was solved by closing the socket. So in the setStop() method (as proposed above) you would have to call serverSocket.close()
(you'd obviously have to make serverSocket a class member or something).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With