2013-05-10 103 views
1

如何在IOException之後重新啓動ServerSocketIOException後重新啓動ServerSocket

我的服務器套接字有時會得到一個EOFException,然後停止接受新的連接。爲了解決這個問題,我嘗試關閉舊服務器套接字並在拋出異常後創建一個新套接字。但是,即使在創建新的服務器套接字後,也不接受新的連接。有人能看出爲什麼這不起作用嗎?

public Server() throws IOException {   
    try { 
    listen(port); 
    } 
    catch (IOException e) { 
    System.out.println("Server() - IO exception"); 
    System.out.println(e); 

    /*when an exception is caught I close the server socket and try opening it a new one */ 
    serverSocket.close(); 

    listen(port); 
    } 
} 

private void listen(int port) throws IOException { 
    serverIsListening = true; 

    serverSocket = new ServerSocket(port); 
    System.out.println("<Listening> Port: " + serverSocket); 

    while (serverIsListening) { 
    if (eofExceptionThrown){ //manually triggering an exception to troubleshoot 
     serverIsListening = false; 
     throw new EOFException(); 
    } 

    //accept the next incoming connection 
    Socket socket = serverSocket.accept(); 
    System.out.println("[New Conn] " + socket); 

    ObjectOutputStream oOut = new ObjectOutputStream(socket.getOutputStream()); 

    // Save the streams 
    socketToOutputStreams.put(socket, oOut); 

    // Create a new thread for this connection, and put it in the hash table 
    socketToServerThread.put(socket, new ServerThread(this, socket)); 
    } 
} 
+0

爲什麼你決定新的連接不接受器?是否拋出了一些異常?或者你不能創建新的套接字?或者它忽略了新客戶? – Taky 2013-05-10 10:56:38

+0

當我在拋出異常並且服務器忽略它時連接一個新客戶端,即它不打印'[New Conn]'消息。 – 2013-05-10 10:58:54

+0

我可能是錯的,因爲我對此不確定。但您可以檢查是否手動觸發了EOF異常。但在你的Server()代碼中,你正在捕獲IOException。確保,如果它有相同的效果。 – Zeeshan 2013-05-10 11:01:31

回答

1

2x入口點,一種形式catch:永遠不會結束。

try { 
    listen(port); 
    } 
    catch (IOException e) { 
    System.out.println("Server() - IO exception"); 
    System.out.println(e); 

    /*when an exception is caught I close the server socket and try opening it a new one */ 
    serverSocket.close(); 

    listen(port); 
    } 

我會做一個循環中,而布爾值爲true:

while(needToListen){ 
    try{ 
    listen(port) 
    }catch(Exception ex){ 
    if(exception is what needed to break the loop, like a message has a string on it){ 
     break; 
    } 
    } 
} 

    if(needToListen){ 
     Log.e("something unexpected, unrecoverable...."); 
    } 
+0

我添加了一個嵌套的'try catch'來覆蓋第二次調用'listen()'。看來問題在於'EOFException'第二次拋出。解決方法是在再次調用'listen()'之前將'eofExceptionThrown'設置爲false。你的回答引導我這樣做,所以我將你標記爲正確的,謝謝。 – 2013-05-10 11:16:43

+0

我很樂意提供幫助 – 2013-05-10 11:17:40

1

我的服務器插槽有時會一EOFException類,然後停止接受新連接

沒有它沒有。 ServerSockets永遠不會得到EOFExceptions。相反,您接受的Sockets之一得到EOFException,這只是預期的,並且您正在關閉Socket,這是正確的,,ServerSocket,這是不正確的。接受的套接字上的異常不會影響偵聽套接字。