简体   繁体   中英

TCP connection - server only sends message after closing socket

I am trying to make a client send a request to a server and receive a response whilst keeping to connection up.

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);

Output on client side

FROM SERVER: Message to send

And after that the connection is lost, obviously.

If i do not close the socket:

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

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

No output on client side. The server never sends the message or the client never receives it.

Anyone knows a possible reason for this to be happening? The client uses a thread to receive messages and a thread to send messages. The client socket is created in the main client thread so receiver and sender threads use the current socket to communicate.

Thanks in advance.

If the client expects to read a line, the server should write a line. A line is terminated by a \\n character.

It may also be necessary to flush 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 say if the flush is required or not.

Never, ever write any code on top of TCP without first specifying the protocol. Otherwise, when you have a problem like this, it's impossible to determine which end is at fault.

One side believes it's sending a "message". The other side does not believe the data it receives is a "message". Which is right? Well, if we had a protocol specification, we'd look at its definition of a "message" and see.

But we don't have one, so we can't say. This makes it impossible to construct a correct fix. If you change the sender to send a line, the receiver will still be broken in requiring a line. Or won't it? And you change the receiver to process messages that aren't lines, is that fixing it or breaking it?

It seems in this case that both sides are wrong. The most likely intent is that a message consists of a line of data terminated with a newline. The sender is not sending a newline and the recipient is not insisting on one either (because it accepts the data as a "message" when the connection closes). So unless the design intent really was that a "message" is a chunk of data not including a line ending terminated by either a line ending or the close of a connection, both sides are wrong.

Document the protocol. It's an essential step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM