Search code examples
javaserversocket

Java Server Socket Interrupt How to


How can I stop a server socket which is listening client. My code look like below

 private ServerSocket serverSocket;

class ServerThread implements Runnable {

    private BufferedReader input;
    public void run() {
    Socket socket = null;

        try {
            serverSocket = new ServerSocket(SERVE_LISTEN_RPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (!Thread.currentThread().isInterrupted()) {

            try {

                socket = serverSocket.accept();
                try {

        this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                     String read = input.readLine();
                                 //Do something
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }


             try {
              serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }
}

I need to stop this thread when I got a command from another thread. I already sow this question but no idea how to implement it.


Solution

  • Here's an example how to close a socket from other thread:

    private static volatile ServerSocket serverSocket;
    
    public static void main(String[] args) throws InterruptedException, IOException {
        Thread serverThread = new Thread(new ServerThread());
        serverThread.start();
        Thread.sleep(1000); // wait a  bit, then close
        serverSocket.close();
    }
    
    static class ServerThread implements Runnable {
    
        private BufferedReader input;
    
        public void run() {
            try {
                serverSocket = new ServerSocket(25);
                while (true) {
                    Socket socket = serverSocket.accept();
                    // client request handling logic
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }