我遇到过python上的一些问题。我尝试用socket.recv(1024)
读取发送的数据,但有时数据的长度超过1024字节。我试试这段代码:
data = b''
received = s.recv(1024)
while len(received) > 0:
data = data + received
received = s.recv(1024)
但是while
循环代码无穷大。我该如何解决?
答案 0 :(得分:2)
以下是您可以如何处理此问题(未经测试):
MINIMUM_PACKET_LENGTH = 100
data = b''
while True:
try:
received = s.recv(1024)
except:
# you might put code here to handle the exception,
# but otherwise:
raise
data = data + received
while len(data) >= MINIMUM_PACKET_LENGTH:
# consume a packet from the data buffer, but leave unused bytes in data
packet = data[0:MINIMUM_PACKET_LENGTH]
data = data[MINIMUM_PACKET_LENGTH:]
# process packet (you could maybe use 'yield packet')
# ....