Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to empty a socket in 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?

like image 471
luc Avatar asked Jul 08 '09 13:07

luc


1 Answers

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.

Spurious readiness notification for Select System call

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

like image 61
Thomas Avatar answered Sep 27 '22 18:09

Thomas