Determine if there is Data left on the socket and discard it

不羁的心 提交于 2019-12-17 14:56:55

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6944414/determine-if-there-is-data-left-on-the-socket-and-discard-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!