2

I'm working on a client-server app. My app is working with variable size packets, each packet has a header and a payload of variable length.

My dilemma is what is the best approach for handing the packets when doing recv. Most of the tutorials I've came across suggest using a ring buffer but as far as I can tell it's more efficient to use a buffer whose size is twice the size of the biggest packet you can handle.

If I use a ring buffer I need an additional buffer for recv and then I need to copy the buffer in the ring buffer which means I need to do one or two memcpys to insert the buffer in the ring buffer

If I use the single buffer approach I only need one buffer which I can pass to recv call and a memmove call to move data to the start of the buffer when I got a full packet and there still is data belonging to another packet in the buffer.

Am I getting something wrong ?

PS. If you can point me to any source code/example where variable length packets are handled that would be helpful.

4

1 回答 1

1

如果我使用环形缓冲区,我需要一个用于 recv 的额外缓冲区,然后我需要将缓冲区复制到环形缓冲区中,这意味着我需要执行一两个 memcpys 以将缓冲区插入环形缓冲区

是的,两次读写,没什么大不了的(*)。但是您不需要额外的缓冲区。对于读取,只需最大化读取到环形缓冲区末尾的剩余空间。

(*):如果您担心额外系统调用的成本,对于分散/收集读/写,有recvmsgsendmsg.

于 2012-03-19T17:35:14.277 回答