• 基于TCP协议的远程终端控制并发socketserver实现以及粘包问题处理


    # 客户端
    
    # -*- coding: utf-8 -*-
    
    import socketserver
    import struct
    import json
    import subprocess
    
    
    class MyTcpHandler(socketserver.BaseRequestHandler):
        def handle(self):
            while True:
                try:
                    cmd = self.request.recv(1024)
                    if not cmd: break
                    print(cmd.decode('utf-8'))
                    obj = subprocess.Popen(cmd.decode('utf-8'),
                                           shell=True,
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE
                                           )
                    stdout = obj.stdout.read()
                    stderr = obj.stderr.read()
                    # 制作报头
                    header_dic = {
                        'file_name': cmd.decode('utf-8'),
                        'data_size': len(stdout) + len(stderr)
                    }
                    header_json = json.dumps(header_dic)
                    header_bytes = header_json.encode('utf-8')
                    # 发送报头字典长度
                    self.request.send(struct.pack('i', len(header_bytes)))
                    # 发送报头
                    self.request.send(header_bytes)
                    # 发送正文
                    self.request.send(stdout + stderr)
                except ConnectionResetError:
                    break
    
    
    if __name__ == '__main__':
        server = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyTcpHandler)
        server.serve_forever()
    

      

    # 服务端
    
    # -*- coding: utf-8 -*-
    
    from socket import *
    import struct
    import json
    
    client = socket(AF_INET, SOCK_STREAM)
    client.connect(('127.0.0.1', 8080))
    
    while True:
        cmd = input('>>>:').strip()
        if not cmd:
            continue
        client.send(cmd.encode('utf-8'))
        # 先接收报头长度并解析
        dic_size = client.recv(4)
        header_size = struct.unpack('i', dic_size)[0]
        # 获取报头字典
        header_json = client.recv(header_size).decode('utf-8')
        header_dic = json.loads(header_json)
        file_size = header_dic['data_size']
        get_size = 0
        info = b''
        while get_size < file_size:
            data = client.recv(1024)
            get_size += len(data)
            info += data
        print(info.decode('gbk'))
    

      

  • 相关阅读:
    基于TFTP协议的远程升级设计
    BZOJ 刷题记录 PART 6
    解决org.hibernate.LazyInitializationException: could not initialize proxy
    在不同版本号hdfs集群之间转移数据
    从零開始制作H5应用(4)——V4.0,增加文字并给文字加特效
    不再安全的 OSSpinLock
    @synchronized 再考察
    ReactiveCocoa
    怎样界定问题
    问题是什么
  • 原文地址:https://www.cnblogs.com/qianzhengkai/p/10821256.html
Copyright © 2020-2023  润新知