客户端没有及时接收缓冲区的包,造成多个包接收(服务端发送了一段数据,客户端只收了一小部分,客户端下次再收的时候还是从缓冲区拿上次遗留的数据,产生粘包)
-------------------------------------------tcp_stickybag_server.py-------------------------------------------
# coding:utf-8
import socket
import subprocess
tcp_server = socket.socket()
ip_port = ("127.0.0.1", 8001)
tcp_server.bind(ip_port)
tcp_server.listen(5)
while 1:
conn, addr = tcp_server.accept()
from_client_msg = conn.recv(1024)
print("来自客户端的消息:", from_client_msg.decode("utf-8"))
res = subprocess.Popen(
from_client_msg.decode("utf-8"),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
conn.send(res.stdout.read())
conn.close()
tcp_server.close()
-------------------------------------------tcp_stickybag_client.py-------------------------------------------
# coding:utf-8
import socket
tcp_client = socket.socket()
ip_port = ("127.0.0.1", 8001)
tcp_client.connect(ip_port)
while 1:
client_input = input("cmd指令1>>>:").strip() # 可以输入dir 或 ipconfig等等
tcp_client.send(client_input.encode("utf-8"))
from_server_msg = tcp_client.recv(1024)
print("来自服务端的消息:", from_server_msg.decode("gbk"))
tcp_client.close()
这种情况,可以尝试调大一次接收数据的最大大小,获取缓存区的大小,方法如下:
# coding:utf-8
import socket
tcp_client = socket.socket()
ip_port = ("127.0.0.1", 8001)
tcp_client.connect(ip_port)
bufsize = tcp_client.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
while 1:
client_input = input("cmd指令1>>>:").strip()
tcp_client.send(client_input.encode("utf-8"))
from_server_msg = tcp_client.recv(bufsize)
print("来自服务端的消息:", from_server_msg.decode("gbk"))
tcp_client.close()
原文:https://www.cnblogs.com/lilyxiaoyy/p/10928247.html