在C++中使用多个recv()和send()调用

huangapple go评论74阅读模式
英文:

Using multipe recv() and send() calls in c++

问题

在C++ TCP套接字编程中,使用多个recv()和send()调用是否在编程上被接受/正确/高效,还是应该使用序列化和其他方法来对数据进行封包/在分隔符处拆分数据?

例如,如果我需要发送多个字符串以存储在多个不同的变量中,我应该将数据打包到一个流中,还是使用多个send/recv调用发送?

英文:

Is it programtically accepted/correct/efficient to use multiple recv() and send() calls in c++ TCP socket programming, or should I use serialization and other methods to packetize my data/ split the data at delimeters?

For instance say I need to send multiple strings to be stored in multiple different variables, should I pack the data in one stream or send using multiple send/recv calls.

答案1

得分: 2

TCP是一种协议。这意味着发送方、接收方或参与通信的任何元素都可以因任何原因拆分或重新组装数据包。

因此,规则如下:

  • 在发送方部分,您可以使用多个send调用发送字节,也可以在发送之前将它们组装在缓冲区中。主要区别在于,由于send是一个真正的系统调用,它会增加一些上下文切换的开销。这就是为什么C和C++库提供了缓冲IO的原因。
  • 在接收方部分,您不能依赖初始数据包的大小不变,而必须按块读取字节并将它们组装起来以重建您的结构(如果重要)。
英文:

TCP is a stream protocol. That means that the sender, the reciever or any element involved in the communication can split or re-assemble packets for any reason.

Because of that, the rules are:

  • on the sender part, you can either send the bytes with many send calls or assemble them in a buffer before sending them. The main difference is that as send is a true system call it adds some overhead for a context change. That is the reason why the C and C++ libraries have provision for buffered IO
  • on the receiver part, you cannot rely on the initial packet sizes to be unchanged but must read bytes in chunks and assemble them to re-build your structures if it matters.

答案2

得分: 2

另一种选择是使用 聚集-分散 I/O 的方式,使用 sendmsg,您可以指定多个缓冲区。也就是说,您可以在不必将多个缓冲区复制到一个缓冲区的情况下获得一个系统调用的好处。

英文:

> For instance say I need to send multiple strings to be stored in multiple different variables, should I pack the data in one stream or send using multiple send/recv calls.

Another option is to use gather-scatter I/O with sendmsg where you can specify multiple buffers. I.e. you get the benefit of one syscall without having to copy multiple buffers into one.

huangapple
  • 本文由 发表于 2020年1月6日 18:40:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定