简体   繁体   中英

How to clear socket buffer to get the latest data from the latest request

I need to clear the socket buffer not to have all the socket "log" inside it. I have to work only with the latest response on my latest request.

I'm using a function to receive all data. I understand that I should somehow empty my socket buffer inside that function, but can't find a way I can do that.

def recv_timeout(the_socket, timeout=2):
    # делаем сокет не блокируемым
    the_socket.setblocking(0)

    total_data = []
    data = ''

    begin = time.time()
    while 1:
        if total_data and time.time() - begin > timeout:
            break

        elif time.time() - begin > timeout * 2:
            break

        try:
            data = the_socket.recv(8192)
            if data:
                total_data.append(data)
                begin = time.time()
            else:
                time.sleep(0.1)
        except:
            pass

    return b''.join(total_data)

When I send request like:

client_socket.sendall('list\r\n'.encode("utf-8"))

I get a normal reply on my request. But when I make

client_socket.sendall('recv 1\r\n'.encode("utf-8"))

immediately after previous request, I get answer 1 + answer 2, but I need only answer 2.

Thanks a lot!

A TCP socket is a stream. All you can do is read everything that has already be received. That means that if your program is like

send req1
receive and process answer1
send req2
receive and process answer2

all should be fine.

But is you do:

send req1
send req2

then you will have to do

receive answer1
receive and process answer2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM