简体   繁体   中英

can one call of recv() receive data from 2 consecutive send() calls?

i have a client which sends data to a server with 2 consecutive send calls:

send(_sockfd,msg,150,0);
send(_sockfd,msg,150,0);

and the server is receiving when the first send call was sent (let's say i'm using select):

recv(_sockfd,buf,700,0);

note that the buffer i'm receiving is much bigger.

my question is: is there any chance that buf will contain both msgs? of do i need 2 recv() calls to get both msgs?

thank you!

TCP is a stream oriented protocol. Not message / record / chunk oriented. That is, all that is guaranteed is that if you send a stream, the bytes will get to the other side in the order you sent them. There is no provision made by RFC 793 or any other document about the number of segments / packets involved.

This is in stark contrast with UDP . As @R.. correctly said, in UDP an entire message is sent in one operation (notice the change in terminology: message ). Try to send a giant message (several times larger than the MTU) with TCP ? It's okay, it will split it for you.

When running on local networks or on localhost you will certainly notice that (generally) one send == one recv . Don't assume that. There are factors that change it dramatically. Among these

  • Nagle
  • Underlying MTU
  • Memory usage (possibly)
  • Timers
  • Many others

Of course, not having a correspondence between an a send and a recv is a nuisance and you can't rely on UDP . That is one of the reasons for SCTP . SCTP is a really really interesting protocol and it is message-oriented .

Back to TCP , this is a common nuisance. An equally common solution is this:

  • Establish that all packets begin with a fixed-length sequence (say 32 bytes)
  • These 32 bytes contain (possibly among other things) the size of the message that follows
  • When you read any amount of data from the socket, add the data to a buffer specific for that connection. When 32 bytes are reached, read the length you still need to read until you get the message.

It is really important to notice how there are really no messages on the wire, only bytes. Once you understand it you will have made a giant leap towards writing network applications.

The answer depends on the socket type, but in general, yes it's possible. For TCP it's the norm. For UDP I believe it cannot happen, but I'm not an expert on network protocols/programming.

Yes, it can and often does. There is no way of matching up sends and receive calls when using TCP/IP. Your program logic should test the return values of both send and recv calls in a loop, which terminates when everything has been sent or recieved.

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