# coding=utf8
"""
:author:徐朋
"""
from queue import Queue
import six
import json
import threading


class TCPMsgParser(object):
    def __init__(self, start_flag=b'\x1e', end_flag=b'\x0a', body_type=dict, msg_parser=None, msg_dealer=None,
                 queue_size=1000):
        self.msg_queue = Queue(queue_size)
        self.body_type = body_type
        self.msg_parser = msg_parser
        self.start_flag = start_flag
        self.end_flag = end_flag
        self.msg_dealer = msg_dealer  # 如果不为None,将启动线程进行消息处理
        if self.msg_dealer:
            threading.Thread(target=self.msg_deal).start()

    def msg_deal(self):
        while True:
            msg = self.get_msg()
            self.msg_dealer(msg)

    def extract_message(self, raw_bytes):
        if len(raw_bytes) < 2:
            return None, raw_bytes
        if six.byte2int(raw_bytes) != six.byte2int(self.start_flag):
            raise Exception(
                'Begin flag lost:%s' % raw_bytes)
        if self.end_flag in raw_bytes:
            b_msg, rest = raw_bytes.split(self.end_flag, 1)
            return b_msg[1:], rest
        else:
            if self.start_flag in raw_bytes[1:]:
                raise Exception(
                    'End flag lost:%s' % raw_bytes)
            return None, raw_bytes

    def _to_deal(self, bbuffer):
        b_msg, bbuffer = self.extract_message(bbuffer)
        while b_msg is not None:
            if self.body_type == dict:
                msg = json.loads(b_msg)
            elif self.body_type == str:
                msg = str(b_msg, encoding='utf8')
            else:
                if self.msg_parser:
                    msg = self.msg_parser(b_msg)
                else:
                    raise Exception('缺少自定义的消息格式解析器.')
            self.msg_queue.put(msg)
            b_msg, bbuffer = self.extract_message(bbuffer)
        return bbuffer

    def __call__(self, bbuffer):
        return self._to_deal(bbuffer=bbuffer)

    def get_msg(self):
        return self.msg_queue.get()

使用说明待更新。