【发布时间】:2023-09-02 00:48:02
【问题描述】:
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));
}
}
【问题讨论】:
-
你为什么决定新的连接不接受?是否抛出了一些异常?或者你不能创建新的套接字?还是只是忽略新客户?
-
当我在抛出异常并且服务器忽略它之后连接新客户端时,即它不打印
[New Conn]消息。 -
我可能错了,因为我不确定。但您可以检查您是否手动触发了 EOF 异常。但是在您的 Server() 代码中,您正在捕获 IOException。确定,如果它有相同的效果。
-
对不起,应该提到
EOFException继承IOException。
标签: java serversocket ioexception