服务器端:
# -*-coding:utf-8-*- # Author:sunhao import socket import os server = socket.socket() ip_port = ('127.0.0.1',6969) server.bind(ip_port) server.listen() while True: conn,f = server.accept() print("new connect:",f) while True: print("等待新指令") data = conn.recv(1024) if not data: print("客户端断开") break print("执行指令",data) res = os.popen(data.decode()).read() print("before send",len(res.encode())) if len(res) == 0: res = "cmd has bo output" conn.send(str(len(res.encode())).encode('utf-8')) #先发数据大小给客户端 会发生粘包 client_ack=conn.recv(1024) #解决粘包 conn.send(res.encode("utf-8")) print("send done") server.close()
客户端:
# -*-coding:utf-8-*- # Author:sunhao import socket client = socket.socket() ip_port = ('127.0.0.1',6969) client.connect(ip_port) print("连接开始") while True: command = input(">>>:").strip() if len(command) == 0: continue client.send(command.encode("utf-8")) cmd_res_size=client.recv(1024) #接受命令结果的长度 print("命令结果的大小",cmd_res_size) client.send("准备好接收了".encode('utf-8')) #解决粘包 recived_size=0 recived_data=b'' while recived_size < int(cmd_res_size.decode()): print("----------",cmd_res_size.decode()) print("##############", type(cmd_res_size.decode())) data=client.recv(1024) print("&&&&&&&&&&",len(data)) recived_size += len(data) #每次收到的有可能小于1024 所以用len判断 recived_data += data else: print("cmd recive done",recived_size) print(recived_data.decode()) client.close()