简体   繁体   中英

Multithreaded server- how to properly handle both client and server disconnect

I am writing a simple multithreaded chat server. Each client is creating new thread while connecting

    Thread listenThread = new Thread(() -> {
        while (true) {
            try {
                Socket client = serverSocket.accept();
                ClientThread handler = new ClientThread(this, client);
                clients.add(handler);
                handler.start();
            } catch (SocketException e) {
                if (e.getMessage().contains("socket closed"))
                    break;

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

This method is good for checking if the client closed the connection.

class ClientThread extends Thread {
    @Override
    public void run() {
        while(running) {
            int read = inputStream.read();
            if(read > 0) {
                // read
            }
            else if(read < 0)
                running = false;        
        }
    }   
};

The problem is that when I want to stop the server, I can't abort the thread because inputStream.read() blocks execution so setting running variable to false has no effect. How to make it work?

  • If you want the server to exit immediately, make the client threads daemon threads.
  • If you want the client threads to close their sockets cleanly, set a shortish read timeout on the accept sockets and have them check your flag every time they get a timeout.
class ClientThread extends Thread {
    @Override
    public void run() {
        String input;
        while(running) {
            input = inputStream.read();
            if(input.lengt > 0) {
                if(input.equals("shutdowncode"))
                    break;
            }       
        }
    }   
};

Send a shutdown code from the server to the client that tells the client to disconnect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM