-------------------------------------------tcp_server.py-------------------------------------------
# coding:utf-8
import socket
import subprocess
server = socket.socket()
ip_port = ("127.0.0.1", 8001)
server.bind(ip_port)
server.listen(5)
conn, addr = server.accept()
from_client_msg = conn.recv(1024)
print("来自客户端的消息:", from_client_msg.decode("utf-8"))
cmd = input(">>>:").strip()
res = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
cmd_result = res.stdout.read()
if res.stderr.read():
cmd_result = res.stderr.read()
cmd_result_len = len(cmd_result)
print(cmd_result_len)
conn.send(str(cmd_result_len).encode("utf-8")) # 先发送数据的长度
from_client_msg = conn.recv(1024)
if from_client_msg.decode("utf-8") == "recv_ready":
conn.sendall(cmd_result) # 再发送真实数据
conn.close()
server.close()
-------------------------------------------tcp_client.py-------------------------------------------
# coding:utf-8
import socket
client = socket.socket()
ip_port = ("127.0.0.1", 8001)
client.connect(ip_port)
client.send("我是客户端.".encode("utf-8"))
from_serve_msg = client.recv(1024) # 接收数据长度
print("来自服务端的消息:", from_serve_msg.decode("utf-8"))
if from_serve_msg.decode("utf-8").isdigit():
from_serve_msg_len = int(from_serve_msg)
client.send("recv_ready".encode("utf-8"))
from_serve_msg = client.recv(from_serve_msg_len) # 接收真实数据
recv_ready_len = len(from_serve_msg)
while from_serve_msg_len > recv_ready_len: # 如果真实数据一次没有接收完
from_serve_msg += client.recv(from_serve_msg_len) # 继续接收数据
recv_ready_len = len(from_serve_msg)
print("来自客户端的消息:", from_serve_msg.decode("gbk"))
client.close()