python 粘包问题的解决
socketserver 模块的使用与粘包问题的解决
基于tcp协议
服务端:
import socketserver
import subprocess
import struct
import json
class MyRequestHandle(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
cmd=self.request.recv(1024)
if cmd.decode('utf8') == 'q':
break
obj=subprocess.Popen(cmd.decode('utf8'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE )
err_res=obj.stderr.read()
std_res=obj.stdout.read()
total_size=len(err_res)+len(std_res)
head_dic={
'file_name':'a.txt',
'total_size':total_size,
'md5':'asdfdfdfsd43432'
}
head_json=json.dumps(head_dic)
head_dic_size=len(head_json)
head_size=struct.pack('i',head_dic_size)
self.request.send(head_size)
self.request.send(head_json.encode('utf8'))
self.request.send(std_res + err_res)
except Exception:
break
self.request.close()
s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyRequestHandle)
s.serve_forever()
客户端:
import socket
import struct
import json
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))
while True:
cmd=input('请输入命令(q退出):').strip()
if len(cmd) == 0: continue
client.send(cmd.encode('utf8'))
if cmd == 'q': break
head = client.recv(4)
head_size=struct.unpack('i',head)[0]
head_json=client.recv(head_size).decode('utf8')
head_dic=json.loads(head_json)
print(head_dic)
total_size=head_dic['total_size']
recv_size=0
while recv_size < total_size:
recv_data=client.recv(1024)
recv_size+=len(recv_data)
print(recv_data.decode('gbk'),end='')
client.close()