如何在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