Hi,
Hoping to get some help with this. I am writing this program that implements a socket server that accepts a single client socket (from a third-party system). This server receives messages from another program and writes them to the client socket. It does not read anything back from the client. However, the client (which I have no control over) disconnects and reconnects to my server at random intervals. My issue is I cannot detect when the client has disconnected (normally or due to a network failure), hence am unable to accept a fresh connection from the client. Here's my code for the server.
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
if (serverSocket == null){
serverSocket = new ServerSocket(4511);
clientSocket = serverSocket.accept();
System.out.println("Accepted client request ... ");
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Input / Output streams intialized ...");
while (true){
System.out.println("Is Client Socket Closed : " + clientSocket.isClosed());
System.out.println("Is Client Socket Connected : " + clientSocket.isConnected());
System.out.println("Is Client Socket Bound : " + clientSocket.isBound());
System.out.println("Is Client Socket Input Shutdown : " + clientSocket.isInputShutdown());
System.out.println("Is Client Socket Output Shutdown : " + clientSocket.isOutputShutdown());
System.out.println("Is Server Socket Bound : " + serverSocket.isBound());
System.out.println("Is Server Socket Closed : " + serverSocket.isClosed());
messageQueue = new MessageQueue(messageQueueDir+"/"+messageQueueFile);
//get Message from Queue Head (also removes it)
message = getQueueMessage(messageQueue);
//format and send to Third Party System
if (message != null){
out.println(formatMessage(message));
System.out.println("Sent to Client... ");
}
//sleep
System.out.println("Going to sleep 5 sec");
Thread.sleep(5000);
System.out.println("Wake up ...");
}
}
}catch(IOException ioe){
System.out.println("initSocketServer::IOException : " + ioe.getMessage());
}catch(Exception e){
System.out.println("initSocketServer::Exception : " + e.getMessage());
}
I never use the client's inputstream to read, although I have declared it here. After the client is connected (it enters the while loop), it prints the following. These values stay the same even after the client disconnects.
Is Client Socket Closed : false
Is Client Socket Connected : true
Is Client Socket Bound : true
Is Client Socket Input Shutdown : false
Is Client Socket Output Shutdown : false
Is Server Socket Bound : true
Is Server Socket Closed : false
So, basically I am looking for a condition that detects that the client is no longer connected, so that I can bring serverSocket.accept() and in and out initializations within the while loop.
Appreciate much, thanks.