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?
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.