python socket 定义协议通信 拆包与粘包

    #dataAnalysis from Client
    def dataAnalysis(self):
        datafmt='<IIIIIIII'
        #定义struct 解包格式,相当协议格式
        fmtLen = struct.calcsize(datafmt)
        #得到协议长度
        while len(self._buffer) >= fmtLen:
            print "Buffer Length:%s" % len(self._buffer)
            (protocLength,) = \
                struct.unpack('<I',self._buffer[:self.HEADERSIZE])
            #取得协议体长度,协议体为protoc
            print protocLength
            if len(self._buffer) == fmtLen+protocLength:
            #得到完整协议+协议体
                HeadStr=self._buffer[:fmtLen]
                #取出协议
                ProtocStr=self._buffer[fmtLen:fmtLen+protocLength]
                srcStr = struct.unpack(datafmt,HeadStr)
                #解包协议格式
                toIP = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])
                #取得IP地址,由整数转换成IP
                print srcStr
                print 'IP is',toIP(srcStr[6])
                
                print '处理protoc'
                print test1
                self._buffer = self._buffer[fmtLen+protocLength:]
                #分包
            elif len(self._buffer) < fmtLen+protocLength:
                print "Continue Received"
                return
            else:
                print "Error"
                self.transport.loseConnection()
                return

posted on 2012-10-17 01:05  Vovolie  阅读(5248)  评论(0编辑  收藏  举报

导航