0

I have a libev based socket server that gets messages from multiple simultaneos sockets

I use recv() to receive message from the socket. And send() to communicate to the socket The problem is that sometimes even if I do a send() and the output of send() is > 0 still the socket on the other side receives nothing

The stripped down version of the code is here http://pastebin.com/SM7uPkVD

(Most of it is cut-pasted from internet )

The problem is that 99% of the times the socket communication works absolutely fine, it is only some places where this fails. Is there some obvious thing I am missing

Ram
  • 1,155
  • 13
  • 34

1 Answers1

0

When using SOCK_STREAM sockets there is no guarantee that multiple sends lead to multiple receives. In particular, your server might read multiple coalesced requests at once in line 124 and then reply only once in line 135, leading you to think that data is being lost. You should check if readlen > 3 to verify this.

jop
  • 2,226
  • 15
  • 16
  • Can there be a no-buffer implementation. Using some other stream. So every write and read will be treated separately – Ram Apr 04 '13 at 11:57
  • This happens for a very good reason: Reducing the IPC overhead. Instead of trying to avoid it, you should aim at taking advantage of it by splitting multiple requests from a large chunk of received data. This can be done by searching for a an end-of-request marker (will `\n\r` do?), prefixing each request with its size, or simply, by having fixed size requests. – jop Apr 04 '13 at 12:39
  • If my data size is guaranteed to be small(less than 1kb) and I can control that too what is the best way of doing a read() or recv(). Should I read 1 character a time an look for a "\r" to end the coversation or change the sender program to prefix a fixed width length – Ram Apr 04 '13 at 13:25
  • 1
    Never read 1 character at a time using `read()` or `recv()`. The overhead is huge. Read as much as you can into an user space `char buffer[]` and then split or iterate over that. The best technique (header or marker) depends on your data format. – jop Apr 04 '13 at 19:13