服务端
import socket
import subprocess
# 创建服务器套接字
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定ip+端口
phone.bind(("127.0.0.1",6668))
# 监听连接,5代表半连接池大小为5
phone.listen(5)
print('服务端启动完成,监听地址为:%s:%s' %('127.0.0.1',8080))
while True:
# #接受客户端链接,返回值为 sock, addr
conn,client_addr = phone.accept()
while True:
try:
# 设置接收大小为1024个bytes
cmd = conn.recv(1024)
obj = subprocess.Popen(cmd.decode("utf-8"),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# 错误示范:if res.stdout: 必须加read() 不然即使里面没有内容,obj.stdout仍为真
res = obj.stdout.read()
if res:
conn.send(res)
# 错误示范:if obj.stderr.read(),stderr中数据只能被读一次,第二次读取将变为空
# 错误示范:conn.send(res.stdout.read()) 此处笔误,则出现报错 res.stdout.read()为空,在TCP中发送空包会阻塞
err_res = obj.stderr.read()
if err_res:
conn.send(err_res)
except Exception:
print("连接出错。")
break
conn.close()
客户端
import socket
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(("127.0.0.1",6668))
while True:
cmd = input("请输入指令:").strip()
if len(cmd) == 0:
continue
phone.send(cmd.encode("utf-8"))
res = phone.recv(1024)
print(res.decode("gbk"))
phone.close()