[英]Multithreaded server- how to properly handle both client and server disconnect
我正在编写一个简单的多线程聊天服务器。 每个客户端在连接时都在创建新线程
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();
}
}
});
此方法适用于检查客户端是否关闭了连接。
class ClientThread extends Thread {
@Override
public void run() {
while(running) {
int read = inputStream.read();
if(read > 0) {
// read
}
else if(read < 0)
running = false;
}
}
};
问题是,当我想停止服务器时,我无法中止线程,因为inputStream.read()
阻止执行,因此将running
变量设置为 false 无效。 如何使它工作?
class ClientThread extends Thread {
@Override
public void run() {
String input;
while(running) {
input = inputStream.read();
if(input.lengt > 0) {
if(input.equals("shutdowncode"))
break;
}
}
}
};
将关闭代码从服务器发送到客户端,告知客户端断开连接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.