从Socket流服务器 - PYTHON3接收多个数据长度

时间:2017-08-13 06:34:02

标签: sockets python-3.6

我间歇性地使用python,我正在使用套接字模块通过API接收来自Broker Application的市场数据和订单数据。我仍然困惑如何编码接收多个数据长度和标题,根据标题信息,我会处理数据。

如何接收多个数据长度并决定使用正确的struct format函数解压缩?

while True:
    try:
        """
        continously receive data from Server API (stock Market data streaming)
        """
        brecvd = self.sock.recv(1024)
        self.brecvdsize = len(brecvd)
        # Unpack the header for correct struct formate to unpack
        unpkr = self.struct.Struct('<lh')
        recvd =self.struct.Struct.unpack_from(unpkr, brecvd)

        Marketdepth = recvd[0] == 284 and recvd[1] == 26
        Indices = recvd[0] == 228 and recvd[1] == 27
        Feed = recvd[0] == 384 and recvd[1] == 22
        BidOffer = recvd[0] == 145 and recvd[1] == 28
        Msg = recvd[0] == 360 and recvd[1] == 99
        #Msg to be checked for 260 or 360

        if Marketdepth:
            self.Marketdepthresponse(brecvd)
            Marketdepth = False

        elif Indices:
            self.Indicesresponse(brecvd)
            Indices = False

        elif Feed:
            self.feedresponse(brecvd)
            Feed = False

        elif BidOffer:
            self.Bidoffer(brecvd)
            BidOffer = False

        elif Msg:
            self.GeneralMsg(brecvd)
            Msg = False

        else:
            Marketdepth = False
            Indices = False
            Feed = False
            BidOffer = False
            Msg = False
            pass


    except Exception as e:
        self.errorcount += 1
        print('***Run Loop Receive Issue: {0}'.format(str(e)))  

1 个答案:

答案 0 :(得分:1)

当您致电def get_message(self): # read the 4-byte length data = self.get_bytes(4) if not data: return None # indicates socket closed if len(data) < 4: raise IncompleteMessageError # process the length and fetch the data length = struct.unpack('>L',data) data = self.get_bytes(length) if len(data) < length: raise IncompleteMessageError return data def get_bytes(self,count): # buffer data until the requested size is present while len(self.buffer) < count: new_data = self.sock.recv(1024) if not new_data: # socket closed remaining,self.buffer = self.buffer,b'' return remaining # return whatever is left. self.buffer += new_data # split off the requested data from the front of the buffer data,self.buffer = self.buffer[:count],self.buffer[count:] return data 时,您可以接收从0(套接字已关闭)到1024字节数据的任何地方。您可能无法获得足够的数据来解压缩完整的消息,可能必须继续接收和缓冲数据,直到您有完整的解包消息,并且可能还会收到下一条消息的一部分。 TCP是一种没有消息边界指示符的流协议。使用TCP的协议必须定义完整消息的外观。

如果没有协议的更多细节,我只能编写一个协议并举例说明。这是完全未经测试但应该给你一个想法。

协议:4字节长度(big-endian),后跟数据字节。

reshape