我正在构建一个 TCP 应用程序,它使用换行符\n
来分隔未知长度的消息(但通常 < 64 字节)。我发现这篇文章非常有用。
最好(即最有效/最快)的方法是recv
一次处理一个字符并检查它是换行符还是recv
更大的缓冲区并将“剩余”存储在类中?
一次一个
def __recv_until_newline(self):
message = ""
while True:
chunk = self.socket.recv(1)
if chunk == "" or chunk == "\n":
break
message += chunk
return message
保持缓冲区
def __recv_until_newline(self):
""" self.__buffer holds previously received message parts"""
message = self.__buffer
while True:
chunk = self.socket.recv(64)
message += chunk
if chunk == "" or "\n" in message:
break
# something a bit more intelligent than this in reality, but you get the idea
messages = message.split('\n')
self.__buffer = "".join([x for x in message[1:]])
return messages[0]