2013-05-10 121 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,这是不正确的。接受的套接字上的异常不会影响侦听套接字。

相关问题