When running and terminating my java program several times using eclipse an exception occurs:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
I am aware that it happens because the socket I opened during the previous execution was not closed.
I tried: (1) Runtime.getRuntime().addShutdownHook to close the SocketServer instance
(2) close the ServerSocket instance in finally block
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();
}
}
}
Can anyone please help me understand how I should solve this and how to properly close the ServerSocket in case of abnormal termination?