How to empty a socket in python?

Posted by luc on Stack Overflow See other posts from Stack Overflow or by luc
Published on 2009-07-08T13:10:12Z Indexed on 2010/05/27 7:41 UTC
Read the original article Hit count: 149

Filed under:
|

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 after 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?

© Stack Overflow or respective owner

Related posts about python

Related posts about sockets