客户端
- 第一步,将字典数据通过json.dumps()函数转为字符串
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)
- 第二步,获取字符长度,结合struct.pack函数保存所发送消息字符长度,连接服务端,发送struct包、发送消息
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() # 关闭套接字...
服务端
- 通过struct.unpack函数解包,获取接受消息长度,通过conn.recv函数分批次接收数据,批次参数之和即为原消息长度,将完整数据拼接后,通过decode函数解码后得到原字符串,再通过json.loads函数转为python字典
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)
网友评论