首页 > 代码库 > socket-1

socket-1

socket 套接字 server端  client端

socket server:

 1 import socket, os
 2 
 3 server = socket.socket()
 4 server.bind(("localhost", 9999))
 5 
 6 server.listen()
 7 
 8 while True:
 9     conn, addr = server.accept()
10     print("new conn:", addr)
11     while True:
12         print("新指令")
13         data = http://www.mamicode.com/conn.recv(1024)
14         if not data:
15             print("客户端断开")
16             break
17         print("执行指令", data)
18         cmd_res = os. popen(data.decode()).read() #接收字符串, 执行结果也是字符串
19         print("before send",len(cmd_res))
20         if len(cmd_res) == 0:
21             cmd_res = "cmd has no output ....."
22 
23         conn.send(str(len(cmd_res.encode())).encode("utf-8"))
24         conn.send(cmd_res.encode("utf-8"))
25         print("send done")
26 
27 server.close()

socket client

 1 import  socket
 2 client = socket.socket()
 3 
 4 
 5 client.connect(("localhost",9999))
 6 
 7 
 8 while True:
 9     cmd = input(">>>:").strip()
10     if len(cmd) == 0:
11         continue
12     client.send(cmd.encode("utf-8"))
13     cmd_res_size = client.recv(1024) # 接收命令结果的长度
14     print("命令结果大小",cmd_res_size)
15     received_size = 0 #每次从ser端 接收的大小
16     received_data = http://www.mamicode.com/b‘‘ #接收的内容 先置空 为bytes
17 
18     while received_size < int(cmd_res_size.decode()): # 接收的内容累加好后
19         data = http://www.mamicode.com/client.recv(1024) #每次最大接收1024个Byte
20         received_size += len(data) # 每次收到的有可能小于 1024 所以用len判断
21         #print(data.decode())
22 
23         received_data += data #把每次接收的数据都叠加
24     else:
25         print("cmd res receive done...",received_size)
26         print(received_data.decode())
27 
28 client.close()

 

socket-1