[英]How to stop the server in a multithreaded client/server application?
How do I get out of the while-loop? 我如何摆脱while循环?
Variable "running" is set TRUE by default and by receiving "shutdown" the value should be changed to FALSE and exit the Thread (the run-method). 变量“ running”默认情况下设置为TRUE,并且通过接收“ shutdown”,该值应更改为FALSE并退出线程(运行方法)。 So the server gets closed after the while-loop.
因此,服务器在while循环后关闭。
ExecutorService executor = Executors.newFixedThreadPool(3);
while (running) {
Socket socket = server.accept();
executor.execute(new Handler(socket,server));
}
executor.shutdown();
server.close();
The run-method: 运行方法:
while(Server.getRunning()){
System.out.println("..Wait for Input!");
String inline = input.readLine();
String[] a = inline.split(" ");
int result;
if (a[0].equals("shutdown")){
Server.setRunning(false);
Protocol.status(client, "shutdown");
return;
}
}
I would suggest you wrap your loop in try-catch for SocketException
and implement something like this: 我建议您将循环包装在try-catch中以获取
SocketException
并实现如下所示的内容:
public synchronized void shutdown()
{
this.running = false;
this.server.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.