如何在python中清空套接字? [英] How to empty a socket in python?
问题描述
我需要清空套接字上的数据(确保没有要接收的内容). 不幸的是,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.
更新-2010-02-27: 当这对关闭时,我注意到了一个错误. inputready总是被套接字填充.我通过添加最大循环数来解决此问题.有更好的解决方法吗?
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?
推荐答案
如果通过刷新"是指丢弃所有待处理的传入数据,则可以像选择一样使用select(),或将套接字设置为非阻塞并读取一直循环,直到没有数据为止.
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.
还要注意这一点(来自Linux联机帮助页):
Also note that (from the Linux manpage):
在Linux下,select()可能将套接字文件描述符报告为就绪" 进行读取",尽管如此,随后的读取仍会阻塞. 例如,当数据到达但发生时,可能会发生 检查的校验和错误并被丢弃.可能还有其他 文件描述符被虚假地报告为的情况 准备好.因此,在应该使用的套接字上使用O_NONBLOCK可能更安全 不会阻止.
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.
这篇关于如何在python中清空套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!