我有一个服务器,它将文本文件的内容发送给它的客户端.
“服务器”包具有“主”(从cmd行args进入端口号并对其进行解析),“服务器”和“ FileHandler”类,我想我已经以某种方式(使用线程池)获得了它们这样服务器就可以同时服务于两个客户端.
现在,我正在尝试构建一个带有选项的CLI,以启动&停止服务器.我正在寻找实现2个线程,其中一个线程将侦听输入,而另一个线程则侦听“ accept()”调用.
到目前为止,我的尝试是创建一个新的类’Commander.java‘,并在构造函数中使用一个AtomicBoolean,然后将其存储在该对象中,以用作停止服务器线程的标志.
我希望正在侦听“ accept()”调用的线程定期检查是否已发出停止请求-如何使用“ Commander”类执行此操作?
包括一些代码片段(到目前为止,我也尝试这样做),以便您更好地理解:
class Server implements Runnable
{
Socket sock;
ExecutorService executor;
private int port ;
public Server(int p) {
port = p ;
executor = Executors.newFixedThreadPool(2);
}
public void startServer() {
ServerSocket s = new ServerSocket(port);
...
while (true)
{
Socket temp = s.accept();
sock = temp;
executor.execute(new FileHandler(sock));
// serveFile(temp) ;
}
public void run() {
startServer();
}
}
public class Main {
public static void main(String[] args) {
while(true) {
System.out.println("Main menu:\n" +
" 1 - Start server\n"+
" 2 - Stop Server\n"+
" 0 - Exit");
int in = Integer.parseInt(scanner.nextLine());
switch(in) {
case 1:
// start server
System.out.println("Starting server...");
Thread th1 = new Thread(new Server(port));
th1.start();
System.out.println("Case continuity...");
// server.startServer() ;
break;
case 2:
// stop server
System.out.println("Server stopped.\n");
break;
case 0:
// exit
System.exit(0);
break;
}
}
}
}
class FileHandler implements Runnable {
Socket socket;
public FileHandler(Socket socket) {
this.socket = socket;
}
private void serveFile() {
...code for serving file...
}
public void run() {
serveFile();
}
}
public class Commander implements Runnable
{
private AtomicBoolean bool;
public Commander(AtomicBoolean bool) {
this.bool = new AtomicBoolean(bool);
}
public boolean value() {
return bool.get();
}
解决方法:
基于@Kayaman Answer:
A-在您的服务器上:
1-让ServerSocket成为类成员范围:
ServerSocket s = new ServerSocket(port);
2-添加方法shutdown():
public void shutdown(){
try{
s.close();
}catch(Exception e){
e.printStacktrace();
}
}
3-添加try / catch来处理套接字关闭(执行干净关闭):
while (true)
{
try{
Socket temp = s.accept();
sock = temp;
executor.execute(new FileHandler(sock));
// serveFile(temp) ;
}catch(SocketException ex){
doAcleanShutdown();
}
}
B-在您的主班:
1-让Server实例成为类成员作用域
Server myServer = new Server(port);
2-在交换机(情况1)中,使用myServer实例
case 1:
// start server
System.out.println("Starting server...");
Thread th1 = new Thread(myServer);
th1.start();
System.out.println("Case continuity...");
// server.startServer() ;
break;
3-停止服务器,情况2:
case 2:
// stop server
myServer.shutdown();
System.out.println("Server stopped.\n");
break;