[python] Clear the socket buffer

When using Socket for network communication in Python, you can socket.recv()receive data by calling a function, and the data will be stored in the buffer. Sometimes, you may want to clear the buffer first so that subsequent data will not be affected by previous data. Here's one way to empty a Python Socket buffer:

import socket

# 创建Socket对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接到服务器
s.connect(('server_ip', port))

# 接收数据,并设置缓冲区大小
buffer_size = 1024
data = s.recv(buffer_size)

# 清空缓冲区
s.setblocking(False)
while True:
    try:
        data = s.recv(buffer_size)
    except socket.error as e:
        break

# 后续处理的事
...

# 关闭Socket连接
s.close()

 In the above code, first set the buffer size. Then, by setting the Socket to non-blocking mode, use a loop to continuously receive the remaining data until there is no data in the buffer. This clears the buffer of the Socket.

It should be noted that during the process of clearing the buffer, if there is no data to receive, socket.recv()an exception will be thrown socket.error. At this time, we can end the loop by catching the exception.

おすすめ

転載: blog.csdn.net/ChaoChao66666/article/details/131958268