https://blog.csdn.net/u013193903/article/details/80739249 struct模块
判断数据大小来解决黏包
mport socket
sk = socket.socket()
sk.bind(('127.0.0.1',8090))
sk.listen()
conn,addr = sk.accept()
while True:
cmd=input('>>>>>>')
if cmd=='q':
conn.send(b'q')
break
conn.send(cmd.encode('gbk'))
num=conn.recv(1024).decode('utf-8')#因为解码
conn.send(b'ok')
res=conn.recv(int(num)).decode('gbk')#需要解码
print(res)
conn.close()
sk.close()
conn.close()
sk.close()
#client
#client
import socket
import subprocess
sk = socket.socket()
sk.connect(('127.0.0.1',8090))
while True:
cmd = sk.recv(1024).decode('gbk')#因为是bytes类型所以需要解码
if cmd=='q':
break
res = subprocess.Popen(cmd,shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
std_out=res.stdout.read()#管道读取只能一次
std_err=res.stderr.read()#管道读取只能一次
sk.send(str(len(std_err)+len(std_out)).encode('utf-8'))
sk.recv(1024)
sk.send(std_out)#因为之前已经读取了
sk.send(std_err)#因为之前已经读取了
sk.close()
struct解决黏包
#client
import socket,struct
import subprocess
sk = socket.socket()
sk.connect(('127.0.0.1',8090))
while True:
cmd = sk.recv(1024).decode('gbk')#因为是bytes类型所以需要解码
if cmd=='q':
break
res = subprocess.Popen(cmd,shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
std_out=res.stdout.read()#管道读取只能一次
std_err=res.stderr.read()#管道读取只能一次
# sk.send(str(len(std_err) + len(std_out)).encode('utf-8'))
# sk.recv(1024)
len_num=len(std_err)+len(std_out)
# print(type(std_err))
# print(len_num)调试
num_by=struct.pack('i',len_num)
sk.send(num_by)
sk.send(std_out)#因为之前已经读取了
sk.send(std_err)#因为之前已经读取了
sk.close()```
#sever
import socket,struct
sk = socket.socket()
sk.bind(('127.0.0.1',8090))
sk.listen()
conn,addr = sk.accept()
while True:
cmd=input('>>>>>>')
if cmd=='q':
conn.send(b'q')
break
conn.send(cmd.encode('gbk'))
# num = conn.recv(1024).decode('utf-8') # 因为解码
# conn.send(b'ok')
num=conn.recv(4)
num=struct.unpack('i',num)[0]
res=conn.recv(int(num)).decode('gbk')#需要解码
print(res)
conn.close()
sk.close()