python 37 粘包问题的解决
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()
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16