khin illua
khin illua

Reputation: 11

Windows Sockets understanding recv and send

I got a little confusion here, say I do this:

send(serverSocks, "Size: 1348", strlen("Size: 1348"), 0)

And then Followed by this:

send(serverSocks, "SomeDataThatIs1348LongAndThatNeedsToBeSent", strlen("SomeDataThatIs1348LongAndThatNeedsToBeSent"), 0)

Since they are sent consecutively, there's a chance that I'll receive it in only one piece when I do something like:

recv(clientSocks, buf, 2000, 0)

Right?

How am I gonna receive it from the server side? Or do I even need the client to send the Size first to the server? Or I could receive the whole data without even knowing the size?

EDIT:

Maybe I need to make my question clearer. How am I gonna tell that this data is a part of this first (or second) data that was sent by the client?

Upvotes: 1

Views: 492

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598031

Since they are sent consecutively, there's a chance that I'll receive it in only one piece when I do something like:

recv(clientSocks, buf, 2000, 0)

Right?

Yes.

How am I gonna receive it from the server side?

You must frame each message in such a way that the receiver knows where one message ends and next begins. You can either:

  1. Send a message's length before sending the message's data. The receiver can then read the length first, then read the specific number of bytes that follow the length.

  2. Append a unique delimiter at the end of each message, something that will never appear in the message data itself, such as an ETX byte, a null terminator, a line break, etc. The receiver can then read bytes until it reaches the delimiter.

Or do I even need the client to send the Size first to the server? Or I could receive the whole data without even knowing the size?

TCP is a streaming transport, it has no concept of message boundaries, so you must handle this in the transmitted data itself.

Upvotes: 1

Related Questions