通过socket连续接收返回数据
- Server服务端
import socket,os server = socket.socket() server.bind(('localhost',9999)) server.listen() while True: conn,addr = server.accept() print("new conn:",addr) while True: data = conn.recv(1024) #第一次没发完会放到io缓冲区 if not data: print("客户端已断开") break print("执行指令",data.decode()) cmd_res = os.popen(data.decode()).read() #接收字符串 print("before send",len(cmd_res)) if len(cmd_res) ==0: #客户端断开后会,服务端收到的是空,数据为0 cmd_res = "cmd has no output..." conn.send(str(len(cmd_res.encode())).encode("utf-8")) #先发大小给客户端 conn.send(cmd_res.encode("utf-8")) server.close()
- Clinet客户端
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_size = client.recv(1024) #接收命令结果长度 print("命令结果大小:",cmd_res_size) received_size = 0 received_data = b'' #创建空的b类型文件 while received_size < int(cmd_res_size.decode()): #如果没传完就继续循环 data = client.recv(1024) #收数据 received_size += len(data) #每次收到的有可能小于1024,所以必须用len判断。 received_data += data #将数据叠加到b文件内 else: print("cmd res receive done",received_size) print(received_data.decode()) client.close()
#recv接收数据后,会先存到缓冲区,缓冲区满了之后会自动send。
#手动send是超时强制向客户端发送数据,不会等待recv填满缓冲区时自动发。
#send发送数据 中文字符=3字节 英文=1字节 缓冲区会多发送len()字符个数。