How to drop/restart a client connection to a flaky socket server
- by Steve Prior
I've got Java code which makes requests via sockets from a server written in C++. The communication is simply that the java code writes a line for a request and the server then writes a line in response, but sometimes it seems that the server doesn't respond, so I've implemented an ExecutorService based timeout which tries to drop and restart the connection.
To work with the connection I keep:
Socket server;
PrintWriter out;
BufferedReader in;
so setting up the connection is a matter of:
server = new Socket(hostname, port);
out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
If it weren't for the timeout code the request/receive steps are simply:
String request="some request";
out.println(request);
out.flush();
String response = in.readLine();
When I received a timeout I was trying to close the connection with:
in.close();
out.close();
socket.close();
but one of these closes seems to block and never return. Can anyone give me a clue why one of these would block and what would be the proper way to abandon the connection and not end up with resource leak issues?