socket发送与接受较大数据量的json(python)

2022-04-24  本文已影响0人  木火应

客户端

    def handle_wechat(self,description,title):
        weChatMessage = self.message
        message = {
            "message": weChatMessage,
            "description": description,
            "title": title,
            "status": 5
        }
        message = json.dumps(message)
        self.send_message(message)
    def send_message(self, message):
        def build_header(data_len):
            header = {'data_len': data_len}
            return json.dumps(header).encode('UTF-8')

        data_len = len(message)
        header = build_header(data_len)
        header_len = len(header)
        struct_bytes = struct.pack('i', header_len)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(("10.0.0.1", 9100))  # 连接服务器 
        sock.send(struct_bytes)
        sock.send(header)
        sock.send(message.encode("utf-8"))
        sock.close()  # 关闭套接字...

服务端

    def send_message(self,conn,addr):
        struct_bytes = conn.recv(4)
        header_len = struct.unpack('i', struct_bytes)[0]
        header_bytes = conn.recv(header_len)
        header = json.loads(header_bytes.decode('UTF-8'))
        data_len = header['data_len']
        # 循环接收数据
        gap_abs = data_len % 1024
        count = data_len // 1024
        recv_data = b''
        for i in range(count):
            data = conn.recv(1024, socket.MSG_WAITALL)
            recv_data += data
        recv_data += conn.recv(gap_abs, socket.MSG_WAITALL)
        recv = recv_data.decode("utf-8")
        resDict = json.loads(recv)
参考: python的socket发送和接收大数据
上一篇下一篇

猜你喜欢

热点阅读