python socket清空接收缓冲区_如何在python中清空套接字?

I need to empty the data on a socket (making sure that there is nothing to receive).

Unfortunately, there is no function for this in the python socket module.

I've implemented something this way:

def empty_socket(sock):

"""remove the data present on the socket"""

input = [sock]

while 1:

inputready, o, e = select.select(input,[],[], 0.0)

if len(inputready)==0: break

for s in inputready: s.recv(1)

What do you think? Is there a better way to do that?

Update: I don't want to change the socket timeout. What's why i prefer a select to a read.

Update: The original question was using the 'flush' term. It seems that 'empty' is a better term.

Update - 2010-02-27 :

I've noticed a bug when the pair has closed. The inputready is always filled with the sockets. I fixed that by adding a maximum number of loops. Is there a better fix?

解决方案

If by "flush" you mean throw away any pending incoming data then you can either use select() like you do, or set the socket to nonblocking and read in a loop until you're out of data.

Also note that (from the Linux manpage):

Under Linux, select() may report a socket file descriptor as "ready

for reading", while nevertheless a subsequent read blocks. This

could for example happen when data has arrived but upon

examination has wrong checksum and is discarded. There may be other

circumstances in which a file descriptor is spuriously reported as

ready. Thus it may be safer to use O_NONBLOCK on sockets that should

not block.

And as has been noted by others, "flush" usually refers to output.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值