使用eclipse多次运行和终止Java程序时,会发生异常:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
我知道发生这种情况是因为我在上一次执行期间打开的套接字没有关闭。
我尝试过: (1)Runtime.getRuntime()。addShutdownHook关闭SocketServer实例
(2)在finally块中关闭ServerSocket实例
public static void main(String ... args) throws Exception {
// propagating Exception(s) to main method for brevity
ServerSocket serverSocket = new ServerSocket(55555, 100,
InetAddress.getByName("localhost"));
System.out.println("Server started at: " + serverSocket);
while (true) {
System.out.println("Waiting for a connection...");
final Socket activeSocket = serverSocket.accept();
System.out.println("Received a connection from " + activeSocket);
Runnable runnable = () -> {
try {
BufferedReader socketReader = null;
BufferedWriter socketWriter = null;
socketReader = new BufferedReader(new InputStreamReader(activeSocket.getInputStream()));
socketWriter = new BufferedWriter(new OutputStreamWriter(activeSocket.getOutputStream()));
String incomingMsg = null;
while ((incomingMsg = socketReader.readLine()) != null) {
socketWriter.write("Response for message: "+incomingMsg+"\r\n"); // Just a dummy code for brevity
socketWriter.flush();
}
} catch(Exception ex) {
// I do nothing here for brevity
}
};
new Thread(runnable).start();
}
}
}
有人可以帮助我了解如何解决此问题以及在异常终止的情况下如何正确关闭ServerSocket吗?