In the class where I have a ServerSocket to listen for incoming connections, below is the code:
while(isRunning) { try { Socket s = mysocketserver.accept(); acknowledgeClient(s); new ClientHandler(s).start(); //Start new thread to serve the client, and get back to accept new connections. } catch(Exception ex) { ex.printStackTrace(); } }
And the following code is acknowledgeClient(Socket s) .
ObjectInputStream in = new ObjectInputStream(s.getInputStream); ObjectOutputStream out = new ObjectOutputStream(s.getOutStream); String msg = in.readObject().toString(); System.out.println(msg+" is Connected");
The run() ClientHandler .
try { in = new ObjectInputStream(client.getInputStream()); out = new ObjectOutputstream(client.getOutputStream()); String msg = ""; while(!msg.equalsIgnoreCase("bye")) { msg = in.readObject().toString(); System.out.println("Client Says - "+msg); out.writeObject("success"); } in.close(); out.close(); } catch(Exception ex) { ex.printStackTrace(); }
And as follows, how the client program interacts with this Echo Server.
try { int count = 10; client = new Socket("localhost",8666); in = new ObjectInputStream(client.getInputStream()); out = new ObjectOutputstream(client.getOutputStream()); out.writeObject("Foo"); System.out.println("Connection Status : "+in.readObject().toString()); while(count>0) { out.writeObject("Hello!"); String resp = in.readObject().toString();
As you can see, after the client has been confirmed after the connection, I close the read / write streams and from the new stream serving the client, I open the stream again and read / write from the connected socket from the server, but as soon as I try to read server response when sending Hello! by the client, it will EOFException instead of receiving success .
I know the reasons why EOF happens, but not understanding why this is happening here, I am not trying to read a socket that has nothing in its stream (it should have success , as written by the server).
It is too early for the client to try to read the socket before the server prints Hello! at its end and wrote success as an answer?
PS: I know that this is not a good way to ask a question by putting so much code, we expect that here we will get answers to this problem and understand this, and not eliminate our problem by others and make sure. So, I have provided this code to show all aspects of the problem.