简体   繁体   English

如何使用socket.recv()获取完全发送的数据?

[英]How to get fully sent data with socket.recv()?

I have faced with some problems on python. 我在python上遇到了一些问题。 I try to read sent data with socket.recv(1024) , but sometime data is very long than 1024 bytes. 我尝试使用socket.recv(1024)读取发送的数据,但有时数据长度超过1024字节。 I try this code: 我尝试以下代码:

data = b''
received = s.recv(1024)
    while len(received) > 0:
        data = data + received
        received = s.recv(1024)

But while loops code infinity. 但是while循环代码无限。 How to i fix it? 我该如何解决?

Here's how you might handle this (untested): 这是您如何处理(未试用)的方法:

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')
        # ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM