1

I am using this server code:

     [...]
     while(1){
       bzero(buffer,256);
       n = read(newsockfd,buffer,255);
       if (n < 0) error("ERROR reading from socket");
       cout << "Message " << buffer << n << endl;
     }
     [...]

On the client side, I have, among other things (this is Java):

out.writeUTF("MOVE");

This line repeats itself several times. But, when I do that, the output I get is:

Message 6

So the n is correct, but the buffer is empty.

I have also tried:

out.writeBytes("MOVE");

And sometimes I get this:

Message MOVE4

But sometimes I get this:

Message M1
Message O1
Message V1
Message E1

So, what can I do? Thank you so much.

1
  • 1
    Well, you could ensure encodings match and understand that TCP is a streaming service and receiving one byte per read call is not an error. Commented Apr 8, 2015 at 17:38

2 Answers 2

2

According to the documentation of the POSIX read function:

If fildes refers to a socket, read() shall be equivalent to recv() with no flags set.

and the documentation of recv says the following

For stream-based sockets, such as SOCK_STREAM, message boundaries shall be ignored. In this case, data shall be returned to the user as soon as it becomes available, and no data shall be discarded.

So you should be prepared to receive incomplete data (after one call to read) or use a message-based socket. Possible ways to deal with incomplete data are passing the message size or using a special value such as NUL char to mark the message end.

Sign up to request clarification or add additional context in comments.

Comments

0

The first example writes the length of the written string as a 16-bit number in front of the actual string. The string is shorter than 256 characters, hence the first byte is 0x00. You need to adjust the way you read the message on the server side. For more information, see this.

In your second example, your problem is that you are not guaranteed that you receive all 4 chars in one buffer. In my opinion, it would be the best to finish your sent string with a null byte and buffer until you receive this byte.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.