简体   繁体   中英

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?

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.

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