判断socket上是否有Data剩余并丢弃 [英] Determine if there is Data left on the socket and discard it

查看:21
本文介绍了判断socket上是否有Data剩余并丢弃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Linux 下编写一个从 TCP 套接字获取数据的接口.用户提供一个缓冲区,其中存储接收到的数据.如果提供的缓冲区太小,我只想返回一个错误.第一个问题是确定缓冲区是否太小.recv() 函数只返回实际写入缓冲区的字节数.如果我使用 recv() 联机帮助页上说明的 MSG_TRUNC 标志,它仍然会返回相同的信息.第二个问题是丢弃仍在套接字中排队的数据.因此,如果我确定我提供的 Buffer 很小,我只想擦除套接字上剩余的所有内容.除了再次关闭和打开套接字或只接收直到没有任何东西之外,还有其他方法吗?最好的问候<

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 <

一个建议是只接收recv,直到没有任何东西为止(我返回0)-但这不会以等待预设超时(在这种情况下为5秒?)而告终,因为每次我调用recv时它都会等待数据或超时?

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?

推荐答案

在 TCP 级别没有关于什么构成应用程序协议消息的知识.然而,有两种最常见的方法来分隔 TCP 流中的消息:

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:

  • 用消息的大小作为前缀并读取那么多字节,或者
  • 读取直到找到特定的字节序列.

有鉴于此,一个通用的 TCP 阅读器应该提供两个通用的阅读功能:

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

  • 读取 N 个字节,以及
  • 读取直到分隔符被读取

类似于Tornado IOStream读取功能的设计会的.

A design similar to Tornado IOStream reading functions would do.

这篇关于判断socket上是否有Data剩余并丢弃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆