search

Home  >  Q&A  >  body text

粘包 - python socket 沾包求助

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

大家讲道理大家讲道理2891 days ago499

reply all(5)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 17:57:50

    Does data have its own defined protocol?

    reply
    0
  • 阿神

    阿神2017-04-17 17:57:50

    Please refer to the writing of socket yourself;

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:57:50

    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~

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:57:50

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:57:50

    You can refer to Twisted’s
    Int32StringReceiver

    reply
    0
  • Cancelreply