实现基于python 3.6。
server端:
1 __author__ = "PyDev2018" 2 3 import socket,os 4 server = socket.socket() 5 server.bind(('127.0.0.1',10090)) 6 7 server.listen() 8 9 while True: 10 conn,addr = server.accept() 11 print("New conn: ",addr) 12 while True: 13 data = conn.recv(1024) 14 if not data: 15 print("客户端已断开!") 16 break 17 print("执行指令:",data) 18 cmd_res = os.popen(data.decode('utf-8')).read() 19 print("命令返回值size:",len(cmd_res)) #这里数据有可能为空 20 if len(cmd_res) == 0: 21 cmd_res = "cmd has no output!" 22 conn.send(str(len(cmd_res.encode('utf-8'))).encode("utf-8")) #先把回显的大小发给客户端,回显可能有中文,先decode一次,防止len错误 23 client_ack = conn.recv(1024) #隔开两次发送数据,防止粘包 24 conn.send(cmd_res.encode('utf-8')) 25 print("命令返回值发送完毕!") 26 server.close()
client端:
1 __author__ = 'PyDev2018' 2 3 import socket 4 client = socket.socket() 5 6 client.connect(('localhost',10090)) 7 8 while True: 9 cmd = input(">>>:").strip() 10 if len(cmd) == 0:continue 11 client.send(cmd.encode("utf-8")) 12 cmd_res_size = client.recv(1024) #接受返回值的大小 13 print("命令返回值的大小为:",cmd_res_size) 14 client.send("已经接收到返回值大小".encode("utf-8")) #防止粘包 15 received_size = 0 #已经接收到的数据大小 16 received_data = b'' 17 while received_size < int(cmd_res_size.decode()): 18 data = client.recv(1024) 19 received_size += len(data) #这里记录总接收的数据 20 received_data += data 21 22 else: 23 print(received_data.decode("utf-8")) 24 print("接收返回值ok!",received_size) 25 26 27 client.close()