Python 为什么连续的socket.makefile调用会丢失传入信息?

Python 为什么连续的socket.makefile调用会丢失传入信息?,python,sockets,Python,Sockets,这是服务器端代码,每三秒逐行读取传入消息 # server side import socket, time with socket.socket() as sock: sock.bind(('', 27182)) sock.listen() _sock = sock.accept()[0] for _ in range(3): time.sleep(3) with _sock.makefile() as file: print(repr

这是服务器端代码,每三秒逐行读取传入消息

# server side
import socket, time

with socket.socket() as sock:
    sock.bind(('', 27182))
    sock.listen()
    _sock = sock.accept()[0]
for _ in range(3):
    time.sleep(3)
    with _sock.makefile() as file:
        print(repr(file.readline()))
# client side
import socket, time

with socket.socket() as sock:
    sock.connect(('127.0.0.1', 27182))
    for s in b'aaa\n', b'bbb\n', b'ccc\n':
        sock.sendall(s)
        time.sleep(2)
这是客户端代码,每两秒钟一行一行地发送消息

# server side
import socket, time

with socket.socket() as sock:
    sock.bind(('', 27182))
    sock.listen()
    _sock = sock.accept()[0]
for _ in range(3):
    time.sleep(3)
    with _sock.makefile() as file:
        print(repr(file.readline()))
# client side
import socket, time

with socket.socket() as sock:
    sock.connect(('127.0.0.1', 27182))
    for s in b'aaa\n', b'bbb\n', b'ccc\n':
        sock.sendall(s)
        time.sleep(2)

这是服务器端的输出,这让我很困惑,因为从客户端发送的部分消息已丢失。为什么会发生这种情况?

为什么要多次调用
.makefile()
?很可能返回的类文件对象正在将所有可用数据读入一个内部缓冲区,然后再拆分第一个完整的行-因此,当您创建一个新对象时,您会丢弃前一个对象缓冲的所有内容。@jasonharper将buffering=0参数传递给makefile()后,现在一切都好了。