通过给服务器输入执行,服务器执行返回结果
服务端:
import socket
import subprocess
server = socket.socket()
ip_port = ('127.0.0.1', 8001)
server.bind(ip_port)
server.listen(5)
print('服务器启动......')
while True:
conn, addr = server.accept()
conn.sendall(bytes('连接服务器成功', encoding='utf-8'))
while True:
try:
recv_byte = conn.recv(1024)
if not recv_byte:
raise Exception('连接断开了')
except Exception as e:
print(e)
break
else:
recv_str = str(recv_byte, encoding='utf-8')
flag, command = recv_str.split("|")
if flag == 'cmd':
# 如果指令错误不会报错,返回错误提示
ret = subprocess.getoutput(command)
ret_bytes = bytes(ret, encoding='utf-8')
length = len(ret_bytes)
print(length)
ret = bytes(str(length),encoding='utf-8')
conn.sendall(ret)
ready = conn.recv(1024)
print(ready)
conn.sendall(ret_bytes)
finally:
pass
客户端
import socket
client = socket.socket()
ip_port = ('127.0.0.1', 8001)
client.connect(ip_port)
print('client start')
recv_bytes = client.recv(1024)
print(str(recv_bytes, encoding='utf-8'))
while True:
command = input('请输入指令:\n>>>').strip()
client.sendall(bytes('cmd|%s' % command, encoding='utf-8'))
total_lenngth = int(str(client.recv(1024), encoding='utf-8'))
recv_length = 0
content_bytes = bytes()
client.sendall(bytes('start accept', encoding='utf-8'))
while recv_length < total_lenngth:
recv_bytes = client.recv(1024)
recv_length += len(recv_bytes)
content_bytes += recv_bytes
ret = str(content_bytes, encoding='utf-8')
print(ret)