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