TCP connection - the server sends the message only after the socket is closed

I am trying to get the client to send a request to the server and receive a response while maintaining the connection.

If I close the socket:

//server side
outToClient.writeBytes("Message to send");
connectionSocket.close();

//client side
serverResponse = inFromServer.readLine(); 
System.out.println("FROM SERVER: " + serverResponse);

      

Client side exit

FROM SERVER: Message to send

And then the connection will be lost, obviously.

If I don't close the socket:

//server side
outToClient.writeBytes("Message to send");

//client side
serverResponse = inFromServer.readLine(); 
System.out.println("FROM SERVER: " + serverResponse);

      

No client side output. The server never sends a message, or the client never receives one.

Does anyone know the possible reason for this? The client uses a stream to receive messages and a stream to send messages. The client socket is created on the client's main thread, so the sender and receiver threads use the current socket for communication.

Thanks in advance.

+3


source to share


2 answers


If the client is waiting to read a string, the server should write a string. The string is terminated with a character \n

.

You may also need to clear the stream you are using to send data to the client:



outToClient.writeBytes("Message to send\n");
outToClient.flush();

      

Without seeing the code, it's hard to tell if you need a flush or not.

+8


source


Never, ever write code over TCP without specifying a protocol. Otherwise, when you have such a problem, there is no way to determine which end is faulty.

One side believes that it is sending a "message". The other party does not consider the received data to be a "message". Which one is correct? Well, if we had a protocol specification, we would go over its definition of "message" and see.

But we don't have it, so we can't say. This makes it impossible to build a correct correction. If you change the sender to send a string, the receiver will still be split into the required string. Or isn't it? And you change the receiver to handle messages that are not lines, is this fixing or breaking it?



In this case, both sides seem to be wrong. The most likely intention is that the message consists of a line of data terminated with a newline character. The sender does not send a newline, and the receiver does not insist on either (as it accepts the data as a "message" when the connection is closed). So if the intent of the project was indeed that the "message" is a piece of data that does not include line termination, ending with either line termination or connection closure, both sides are wrong.

Document the protocol. This is an important step.

+3


source







All Articles