Exit stream

I have the following 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 stopFlag is set to true. serverSocket.receive(receivePacket);will wait for the package. What if I want the thread to exit as soon as stopFlag is set to true.

+5
source share
4 answers

I had the same problem with the socket, and interruption () did not work. My problem was solved by closing the socket. Therefore, in the setStop () method (as suggested above) you would need to call serverSocket.close()(you obviously would need to make serverSocket a member of the class or something else).

+6
source

I'm not sure where the stop flag comes from, but in any case the answer is interrupted.

Thread t;
ServerSoket serverSoket;

public void startListening() throws Exception {
    ...
    serverSocket = new DatagramSocket(port);
    t = new Thread()...;
    t.start();
    ...
}

setStop() {
    stopFlag = true;
    serverSocket.close()
    t.interrupt();
}
+2
source

This will help if you have code that includes the code in which you plan to change stopFlag. If it is outside the stream, you can probably use .interrupt()in the stream, followed by .destroy()the stream. This is not an ideal solution, which is better, perhaps try to add a timeout to your server socket, see the setSoTimeout()method DatagramSocketin java api.

+2
source

Use serverSocket.setSoTimeout(t).

0
source

All Articles