您可以使用socket.makefile()将套接字包装在类似文件的对象中。然后,读取将精确返回所请求的数量,除非套接字在关闭时可以返回剩余数量。这是一个例子:
server.py
from socket import *sock = socket()sock.bind(('',5000))sock.listen(1)with sock: client,addr = sock.accept() with client, client.makefile() as clientfile: while True: data = clientfile.read(5) if not data: break print(data)client.py
from socket import *import timesock = socket()sock.connect(('localhost',5000))with sock: sock.sendall(b'123') time.sleep(.5) sock.sendall(b'451234') time.sleep(.5) sock.sendall(b'51234')服务器输出
12345123451234



