Twisted's protocol.datareceived () can handle the raw data received, since it is original, it may be different from the "package" defined by the application layer, that is, sticky packets and sub-packages are difficult to avoid
Look at the code that handles the sticky pack:
#!/usr/bin/env python#coding=utf-8 import structdef mypack (data): pack_format = ' 2i%ds ' return struct.pack (Pack_format % len ( Data), 100,len (data), data) #简单解码def myunpack (data): pack_ format = ' 2i%ds ' % (len (data) - 2*4) return Struct.unpack (pack_format,data) #解码 + handling Sticky pack def myunpack2 (data): pack_format = ' 2i%ds ' % (len (data) - 2*4) (VERSION,LENGTH,STR) = struct.unpack (Pack_format,data) if 0 < (len (data) - 2*4)-length): #如果有粘包, the subsequent fields are Put in a string pack_format = ' 2i%ds%ds ' % (length , (len (data) - 2*4)-length) return struct.unpack (pack_format,data) else: return (VERSION,LENGTH,STR) #测试if __name__ == ' __main__ ': import json str = {' A ': 1111, ' B ': [], ' C ': ' Asfasdf '} str = json.dumps (str) a = mypack (str) print a b = myunpack2 (a+a+a) print b while 3<len (b): b = myunpack2 (b[3]) print b
Sub-package is relatively simple, that is, the last output of B to judge
If b[1] > len (b[2]): #分包了, the last data is placed in a temporary variable, waiting for the next data stream to process the pass
-----------------------------------------
Python's unpack function is not as powerful as PHP, and PHP's unpack can support matching patterns like * (any number)