簡體   English   中英

如何在多線程客戶端/服務器應用程序中停止服務器?

[英]How to stop the server in a multithreaded client/server application?

我如何擺脫while循環?

變量“ running”默認情況下設置為TRUE,並且通過接收“ shutdown”,該值應更改為FALSE並退出線程(運行方法)。 因此,服務器在while循環后關閉。

ExecutorService executor = Executors.newFixedThreadPool(3);
        while (running) {
            Socket socket = server.accept();
            executor.execute(new Handler(socket,server));
        }
        executor.shutdown();
        server.close();

運行方法:

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;
            } 
}

我建議您將循環包裝在try-catch中以獲取SocketException並實現如下所示的內容:

public synchronized void shutdown()
{
   this.running = false;
   this.server.close();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM