• 解决粘包-复杂版


    服务端:
    import socket
    import subprocess
    import json
    import struct

    server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server.bind(('192.168.43.177',8095))
    server.listen(5)
    while True:
    conn,client_addr = server.accept()
    while True:
    try:
    cmd = conn.recv(8096)
    if not cmd :break
    #数据解析
    obj = subprocess.Popen(cmd.decode('utf-8'),shell=True,
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE)
    stdout = obj.stdout.read()
    stderr = obj.stderr.read()
    total_size = len(stdout)+len(stderr)
    header = {'filename':'djaidj',
    'total_size':total_size
    }
    header_json = json.dumps(header)
    header_bytes = header_json.encode('utf-8')
    conn.send(struct.pack('i',len(header_bytes)))
    conn.send(header_bytes)
    conn.send(stdout)
    conn.send(stderr)
    except ConnectionResetError:
    break
    conn.close()
    server.close()

    客户端

    import socket
    import subprocess
    import json
    import struct

    client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    client.connect(('192.168.43.177',8095))
    while True:
    cmd = input('>>:').strip()
    if not cmd:continue
    client.send(cmd.encode('utf-8'))

    obj = client.recv(4)
    header_size = struct.unpack('i',obj)[0]
    header_bytes = client.recv(header_size)
    header_json = header_bytes.decode('utf-8')
    header = json.loads(header_json)
    total_size = header['total_size']
    recv_data = b''
    recv_size = 0
    while recv_size < total_size:
    res = client.recv(1024)
    recv_data += res
    recv_size += len(res)
    print(recv_data.decode('gbk'))
    client.close()
  • 相关阅读:
    组合模式/composite模式/对象结构型模式
    迭代器模式/iterator模式/对象行为型模式
    复制Eclipse工作空间设置
    各种命令
    Java相关框架
    基于hk2框架的功能测试Mock注入
    个人项目----词频统计(补全功能)
    小组项目----用户需求调查
    四人小组项目申请
    补第一周“四人小组项目“
  • 原文地址:https://www.cnblogs.com/rainbowupdate/p/12255917.html
Copyright © 2020-2023  润新知