服务端:
# Author:Winter Liu is coming! import socket import os server = socket.socket() server.bind(("localhost", 9999)) server.listen() while True: conn, addr = server.accept() print("新连接建立", addr) while True: print("等待命令!") data = conn.recv(1024) # buffer大小,建议最大8K,返回编码数据 if not data: print(addr, "客户端断开!") break print("执行指令:", data.decode()) # 注意解码 cmd_res = os.popen(data.decode()).read() # 调用命令 print(len(cmd_res)) if len(cmd_res) == 0: # 判断命令是否被执行 cmd_res = "输入错误" # 先发送执行结果字符串的长度 # 注意len返回中文长度会和实际不一致 # 注意粘包问题 conn.send(str(len(cmd_res)).encode("UTF-8")) print(conn.recv(1024).decode()) conn.send(cmd_res.encode("UTF-8")) cmd_res = "" server.close()
客户端:
# Author:Winter Liu is coming! import socket client = socket.socket() client.connect(("localhost", 9999)) while True: cmd = input(">>>").strip() if len(cmd) == 0: continue client.send(cmd.encode("UTF-8")) # 发送的数据要编码 # 注意粘包的问题 # 当连续发送时,有可能出现两次数据连接到一起 cmd_res_len = client.recv(1024).decode() # 获取待发送数据长度 client.send("准备接收数据:".encode()) cmd_res_len = int(cmd_res_len) # 注意转换为整数 recv_data = "" recv_size = 0 while recv_size < cmd_res_len: # 判断是否接受完成 data = client.recv(1024) recv_size += len(data) print(recv_size, len(data)) recv_data += data.decode() else: print("执行完毕!") print(recv_data) print(len(recv_data)) client.close()