使用Python中select()清空TCP通讯缓冲区数据。

发布于 2022-05-06  1307 次阅读


Python的select()⽅法直接调⽤操作系统的IO接⼝,通过操作系统提供的⽹络接⼝进⾏操作,不通过Python解释器。

import socket
import struct
import numpy as np
import select

def clearSocketBuffer(conn:socket.socket):
    while True:
        #监听conn状态0.1S一次
        ready = select.select([conn], [], [], timeout_in_seconds)  
        #取出之前的数据
        if ready[0]:
            data = conn.recv(1024)
            print("清空数据:", data)
        else:
            print('超时清空')
            return

ip_port = ('192.168.3.1', 28888)

#创建客户端建立连接
sk = socket.socket()
sk.connect(ip_port)    
sk.setblocking(False) # 需要先设置为非阻塞, 使用select超时机制清空
timeout_in_seconds = 0.1

clearSocketBuffer(sk)  #启动

sk.setblocking(True) # 设置阻塞, 等待数据读取
while True:
    data = sk.recv(4)
    size = struct.unpack('i', data)[0]
    print("接收数据大小:", size)
    data = sk.recv(size)
    print("数据:", data)