Reputation: 23
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.
Upvotes: 1
Views: 532
Reputation: 55685
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.
Upvotes: 2
Reputation: 3679
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.
Upvotes: 0