如何在IOException
之后重新启动ServerSocket
?IOException后重新启动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));
}
}
为什么你决定新的连接不接受器?是否抛出了一些异常?或者你不能创建新的套接字?或者它忽略了新客户? – Taky 2013-05-10 10:56:38
当我在抛出异常并且服务器忽略它时连接一个新客户端,即它不打印'[New Conn]'消息。 – 2013-05-10 10:58:54
我可能是错的,因为我对此不确定。但您可以检查是否手动触发了EOF异常。但在你的Server()代码中,你正在捕获IOException。确保,如果它有相同的效果。 – Zeeshan 2013-05-10 11:01:31