标签:NPU back 现象 代码 format bin lis strip() col
服务器端
import socket sk = socket.socket() sk.bind(("127.0.0.1", 6666)) sk.listen() conn, address = sk.accept() def my_send(msg): bs = msg.encode("utf-8") len_str = format(len(bs), "04d") # 定长4位 conn.send(len_str.encode("utf-8")) conn.send(bs) my_send(input(">>>:").strip()) my_send(input(">>>:").strip())
客户端
import socket import time sk = socket.socket() sk.connect(("127.0.0.1", 6666)) time.sleep(10) # 制造粘包情况 msg = sk.recv(1024).decode("utf-8") # 粘包现象 print(msg)
执行结果:
0004aaaa0003bbb
有粘包的现象。
解决粘包,客户端代码调整
import socket import time sk = socket.socket() sk.connect(("127.0.0.1", 6666)) time.sleep(10) def my_recv(): len_str = int(sk.recv(4).decode("utf-8")) msg = sk.recv(len_str) print(f"来自服务端的消息:{msg.decode(‘utf-8‘)}") my_recv() my_recv()
执行结果:
来自服务端的消息:aaaa
来自服务端的消息:bbb
标签:NPU back 现象 代码 format bin lis strip() col
原文地址:https://www.cnblogs.com/lilyxiaoyy/p/12002690.html