标签:strip connect end close serve strip() listen 客户 input
[TOC]
#struct模块解决黏包问题
cat tcp_server.py
```
#server 下发命令给客户端执行
import socket,struct
sk = socket.socket()
sk.bind(("127.0.0.1", 8989))
sk.listen()
conn,add = sk.accept()
while True:
cmd = str(input("CMD:")).strip()
conn.send(cmd.encode("utf-8"))
if cmd == ‘q‘:
break
ret = conn.recv(4)
len_num = struct.unpack("i", ret)
res = conn.recv(len_num[0])
print(res)
conn.close()
sk.close()
```
cat tcp_client.py
```
sk = socket.socket()
sk.connect(("127.0.0.1", 8989))
while True:
cmd = sk.recv(1024)
if cmd.decode("utf-8") == ‘q‘:
break
res = subprocess.Popen(cmd,shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
std_out = res.stdout.read()
std_err = res.stderr.read()
len_num = len(std_out) + len(std_err)
ret = struct.pack("i", len_num)
sk.send(ret)
sk.send(std_out)
# print(std_out)
sk.send(std_err)
# print(std_err)
sk.close()
```
标签:strip connect end close serve strip() listen 客户 input
原文地址:https://www.cnblogs.com/rootid/p/9535778.html