• 解决粘包问题终极方法


    解决粘包问题终极方法

    #server粘包
    import socket
    import subprocess
    import struct
    soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    soc.bind(('127.0.0.1',8001))
    soc.listen(3)
    while True:
        print('等待客户端连接')
        conn,addr=soc.accept()
        print('有个客户端连接上了',addr)
        while True:
            try:
                data=conn.recv(1024)
                if len(data)==0:
                    break
                print(data)
                obj = subprocess.Popen(str(data,encoding='utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                #执行正确的结果 b 格式,gbk编码(windows平台)
                msg=obj.stdout.read()
    
                #发送的时候需要先把长度计算出来
                #头必须是固定长度
                #先发4位,头的长度
                import json
                dic={'size':len(msg)}
                dic_bytes=(json.dumps(dic)).encode('utf-8')
                #head_count是4个字节的长度
                head_count=struct.pack('i',len(dic_bytes))
                print(dic)
                conn.send(head_count)
                #发送头部内容
                conn.send(dic_bytes)
                #发了内容
                conn.send(msg)
            except Exception:
    
                break
        # 关闭通道
        conn.close()
    
    
    # 关闭套接字
    soc.close()
    
    #client模块
    import socket
    import struct
    import json
    soc=socket.socket()
    
    soc.connect(('127.0.0.1',8001))
    while True:
        in_s=input('请输入要执行的命令:')
        soc.send(in_s.encode('utf-8'))
        #头部字典的长度
        head_dic_len=soc.recv(4)
        #解出真正的长度
        head_l=struct.unpack('i',head_dic_len)[0]
        #byte 字典的长度
        #收真正的头部字典
        dic_byte=soc.recv(head_l)
        head=json.loads(dic_byte)
        print(head)
        l=head['size']
        count=0
        data_total=b''
        print(l)
        while count<l:
            if l<1024: #如果接受的数据小于1024 ,直接接受数据大小
                data=soc.recv(l)
            else:#如果接受的数据大于1024
                if l-count>=1024: #总数据长度-count(目前收到多少,count就是多少) 如果还大于1024  ,在收1024
                    data=soc.recv(1024)
                else: #总数据长度-count(目前收到多少,count就是多少) 如果小于1024,只收剩下的部分就可
                    data=soc.recv(l-count)
    
            data_total+=data
            count+=len(data)
    
        print(str(data_total,encoding='gbk'))
    
  • 相关阅读:
    ASP.NET和PHP全面对比
    GridView事件DataBinding,DataBound,RowCreated,RowDataBound区别及执行顺序分析
    OA、CRM、ERP之间的区别和联系是什么?
    C#继承
    对软件项目管理的几点认识
    冒泡
    经典排序算法
    asp.net遍历页面中所有TextBox,并赋值为String.Empty的方法
    String.Format用法
    frame和iframe
  • 原文地址:https://www.cnblogs.com/aden668/p/11478436.html
Copyright © 2020-2023  润新知