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.
Does data have its own defined protocol?
Please refer to the writing of socket yourself;
Provide some ideas:
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