2012-03-18 244 views
1

我創建一個服務器客戶端程序,客戶端根據服務器的響應向服務器發送特定信息。 對於不斷從多個客戶端偵聽,我有一個線程在服務器上不斷偵聽客戶端請求。無論何時收到請求,我啓動另一個線程併發送該套接字運行並開始監聽其他客戶端的請求。在java中殺死線程

這裏是代碼連續聽

while(true){ 
    //serverListener is a ServerSocket object 
    clientSocket = serverListener.accept();//Waiting for any client request 

    //New thread started when request is received from any client 
    Thread thread =new Thread(new serverThread(clientSocket), "ClientThread"); 
    thread.start(); 
} 

現在我的問題是,如何才能停止服務器。我知道在while循環中使用boo lean變量,然後更改值的一種替代方法,但問題是當線程正在等待獲取任何連接時,更改布爾變量的值也不會停止服務器。

有什麼辦法可以解決這個問題。

+0

1級的解決方案,我發現是使用服務器套接字超時,然後使用布爾變量檢查服務器是否停止。 – Zlatan 2012-03-18 18:32:48

回答

0

ServerSocket#setSoTimeout()可能會引起您的興趣,如果達到超時,它將放棄接受。注意捕捉SocketTimeoutException。

+0

超時可以是解決方案之一,但我不想阻止它聽從 – Zlatan 2012-03-18 18:26:39

+1

您可以將accept()放入循環中。超時檢查是否請求停止。如果不是,再次接受()。 – PeterMmm 2012-03-18 18:34:51

3

通常serverListener(我認爲其實是一個ServerSocket什麼的)被另一個線程關閉。這將在accept()中生成java.net.SocketException,這將終止循環和線程。

final ServerSocket serverSocket = new ServerSocket(8000); 
new Thread(new Runnable() { 
    public void run() { 
     while (true) { 
      try { 
       serverSocket.accept(); 
      } catch (IOException e) { 
       return; 
      } 
     } 
    } 
}).start(); 
Thread.sleep(10000); 
serverSocket.close(); 
+0

我已經嘗試過這種方法,IO異常仍在服務器上運行。 – Zlatan 2012-03-18 18:10:14

+0

@Meherzad「仍服務器正在運行」是什麼意思?關閉後,套接字不應綁定到端口。你的意思是線程仍在運行?該程序不關機? – Gray 2012-03-18 18:13:37

+0

嘗試設置setDaemon(true)。在啓動之前在服務器接受線程上調用它。客戶端 - 服務器線程也將成爲守護進程線程。服務器應用程序應該退出。 – 2012-03-18 18:18:52

0
volatile boolean finishFlag = false; 

while(true){ 

      clientSocket = serverListener.accept();//Waiting for any client request 

      if (finishFlag) 
       break; 

      //New thread started when request is received from any client 
      Thread thread =new Thread(new serverThread(clientSocket), "ClientThread"); 
      thread.start(); 
} 

編輯:

打斷聽衆,你應該從外部阻止這個線程,然後接受()將拋出IOException異常

try { 
     while (true) { 
     Socket connection = server.accept(); 

     try {  
      // any work here  
      connection.close(); 
     } 
     catch (IOException ex) { 
     // maybe the client broke the connection early. 
     } 

     finally { 
     // Guarantee that sockets are closed when complete. 
     try { 
      if (connection != null) connection.close(); 
     } 
     catch (IOException ex) {} 
    }  
    }  
    catch (IOException ex) { 
    System.err.println(ex); 
    } 
+0

它繼續等待accept(),直到接收到新客戶端的客戶端請求時纔會進入下一行。我已經嘗試過這種情況,並在問題中提到了這一點。 – Zlatan 2012-03-18 18:13:11