1.服務端程式碼
import socket, os
server = socket.socket()
server.bind(('localhost',22222))
server.listen()
while True:
conn, addr = server.accept()
print("new conn:", addr)
while True:
data = conn.recv(1024)
if not data:
print("客戶端已斷開")
break
print("執行指令", data)
cmd_res = os.popen(data.decode("utf-8")).read()
if len(cmd_res) == 0:
cmd_res = 'cmd has no output...'
conn.send(str(len(cmd_res)).encode("utf-8")) #conn.send(str(len(cmd_res.encode("utf-8"))).encode("utf-8")) 這樣客戶端後面可用=號,一箇中文三個位元組
conn.send(cmd_res.encode("utf-8"))
server.close()
2.客戶端程式碼
import socket
client = socket.socket()
client.connect(('localhost', 22222))
while True:
cmd = input(">>:").strip()
if len(cmd) == 0: continue
client.send(cmd.encode("utf-8"))
cmd_res_size = client.recv(1024) #接受命令結果的長度
received_size = 0
received_data = b''
while received_size < int(cmd_res_size.decode("utf-8")):
data = cmd_res = client.recv(1024)
received_size += len(data)
#print(data.decode("utf-8"))
received_data += data
else:
print("cmd res receive done...", received_size)
print(received_data.decode("utf-8"))
client.close()