粘包 - python socket 沾包求助
大家讲道理
大家讲道理 2017-04-17 17:55:50
0
5
498

1:公司要通过socket的方式请求服务器拿数据,recv返回回来后要判断数据是否完整,是否在完成一条后还有下一条数据,从没有写过沾包,想求助具体写法,返回数据的形式是 长度 code 内容。这个接收的方法单独起一个现成while 循环来跑 不停地跑

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(5)
左手右手慢动作

Does data have its own defined protocol?

阿神

Please refer to the writing of socket yourself;

伊谢尔伦

Provide some ideas:

buffer = ''
while 1:
    data = recv() # 注意处理各种异常,recv有可能返回非str
    if not data:
        continue
    buffer += data
    while buffer:
        pack_len = ... # 取长度 (长度值必然是占固定的位数)
        if len(buffer) < pack_len:
            break
        pack = buffer[:pack_len] # 取包
        handle(pack) # 处理一个包
        buffer = buffer[pack_len:] # 从缓存中删除包

TCP packets must be stuck to the same peer. The peer is not processed here. You have to do the same processing for each peer
Don’t add the data of different peers together~

迷茫

If you use a custom protocol, add a length field to the message. Based on this length, you can know the length of this message and whether there is the next piece of data.

洪涛

You can refer to Twisted’s
Int32StringReceiver

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template