Python's sticky bag and subcontracting

Source: Internet
Author: User
Tags unpack

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.