2011-05-25 375 views
3

在我的服務器應用程序,我試圖處理它使用的ServerSocket類的服務器,關閉監聽的ServerSocket

  1. 啓動服務器,等待連接。
  2. 停止與客戶端連接的服務器。
  3. 停止正在等待客戶端的服務器。

我可以能夠啓動該服務器並使其等待客戶端線程中使用

socket = serverSocket.accept(); 

我想做什麼是我要手動關閉其正在等待連接的插座,我使用都試過了,

if (thread != null) { 
    thread.stop(); 
    thread = null; 
    } 
    if (socket != null) { 
    try { 
     socket.close(); 
     socket = null; 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

執行,即使插座變爲空,當我嘗試從客戶端連接到服務器上面的代碼後,連接被建立起來,所以我的問題是如何中斷的ServerSocket WHI ch在這裏監聽連接,

socket = serverSocket.accept(); 

回答

2

只需關閉ServerSocket,並捕獲由此產生的SocketClosedException

並擺脫thread.stop()。爲什麼,see the Javadoc

+0

沒有'SocketClosedException',只有'java.net.SocketException:socket closed' – 2015-09-24 11:28:32

4

我認爲處理這種情況的一種常見方式是使accept()調用超時在循環中。

因此,像:

ServerSocket server = new ServerSocket(); 
server.setSoTimeout(1000); // 1 second, could change to whatever you like 

while (running) { // running would be a member variable 
    try { 
     server.accept(); // handle the connection here 
    } 
    catch (SocketTimeoutException e) { 
      // You don't really need to handle this 
    } 
} 

然後,當你想關閉您的服務器,只是已經代碼中設置「跑步」爲假,它會關閉。

我希望這是有道理的!

+0

Hi Phill Sacre,實際上我不想修復一個時間限制,我希望用戶無論是在監聽還是連接到客戶端,都希望控制開始和停止時間,這是否可能。 – Vignesh 2011-05-25 07:55:40

+0

Hi Phill Sacre,我試過你的建議,我在1分鐘後修正了60000毫秒我得到SocketTimeoutException,但仍然在客戶端可以連接服務器在特定的套接字,任何想法? – Vignesh 2011-05-25 10:05:51

+0

@Vignesh因爲你還沒有關閉ServerSocket。 – EJP 2011-08-29 08:14:44