gpt4 book ai didi

java - IOException 后重新启动 ServerSocket

转载 作者:行者123 更新时间:2023-11-30 04:23:16 27 4
gpt4 key购买 nike

如何在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));
}
}

最佳答案

2 个入口点,一个表单捕获:永远不会有好结果。

  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);
}

当 boolean 值为 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....");
}

关于java - IOException 后重新启动 ServerSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16480580/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com