Determine if there is Data left on the socket and

2020-01-29 21:33发布

I'm writing an Interface under Linux which gets Data from a TCP socket. The user provides a Buffer in which the received Data is stored. If the provided Buffer is to small I just want to return an Error. First problem is to determine if the Buffer was to small. The recv() function just returns me the amount of bytes actually written into the Buffer. If I use the MSG_TRUNC flag stated on the recv() manpage it still returns me the same. Second problem is to discard the data still queued in the socket. So if I would determine that my provided Buffer was to small I just want to erase everything which is left on the socket. Is there any other ways to do so except Closing and opening the socket again or just receive until nothing is left? Best Regards <

One suggestion was to just recv until nothing is left ( I get returned 0 ) - but wouldnt that end in having to wait for the preset timeout ( in this case it's 5 sec? ) because everytime I call the recv it waits for data or timeout?

2条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-29 21:49

Your design has a flaw.

If a client provides a buffer that's too small, how do you know how much data to discard? Is there something in the data that tells you when you've reached the end of the message to be discarded? If that's the case, then you need to buffer the input stream in your code so you can detect these boundaries. If your code sees the stream as undifferentiated bytes, then your question doesn't make sense, as your code cannot in principle know when to stop discarding data. With TCP streams, unless there's an embedded protocol that delimits "messages", then it's all-or-nothing up until the connection is closed.

查看更多
家丑人穷心不美
3楼-- · 2020-01-29 21:50

There is no knowledge at TCP level about what constitutes an application protocol message. There are, however, two most common ways to delimit messages in a TCP stream:

  • prefix messages with their size and read that many bytes, or
  • read till a certain sequence of bytes is found.

In this light, a generic TCP reader should provide two reading functions to be universally useful:

  • to read N bytes, and
  • to read till a delimiter has been read

A design similar to Tornado IOStream reading functions would do.

查看更多
登录 后发表回答