码迷,mamicode.com
首页 > 编程语言 > 详细

python 37 粘包问题的解决

时间:2020-04-21 23:54:26      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:ase   inpu   txt   import   eve   gbk   tin   基于   head   

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()

python 37 粘包问题的解决

标签:ase   inpu   txt   import   eve   gbk   tin   基于   head   

原文地址:https://www.cnblogs.com/Franciszw/p/12748608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!