python socketserver实现客户端多并发

时间:2022-03-26 06:08:04

 

 

 

直接看代码

server

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socketserver
import subprocess

class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        print("got connection from",self.client_address)
        while True:
            conn = self.request
            data = conn.recv(1024)
            if not data:break
            print (str(data,'utf8'))
            cmd = str(data,'utf8')
            cmd_call = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
            cmd_result = cmd_call.stdout.read()
            if len(cmd_result) == '0':
                cmd_result = b'no output'
            ack_msg = bytes("CMD_RESULT_SIZE|%s" %len(cmd_result),'utf8')
            conn.send(ack_msg)
            client_ack = conn.recv(50)
            if client_ack.decode() == 'CLIENT_READY_TO_RECV':
                conn.send(cmd_result)

if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(('localhost',8091),MyServer)
    server.serve_forever()

 

client

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
ip_port = ('localhost',8091)
sk = socket.socket()
sk.connect(ip_port)
print ("客户端启动:")

while True:
    user_input = input("cmd:").strip()
    if len(user_input) == 0:continue
    if user_input == 'q':break
    sk.send(bytes(user_input,'utf8'))
    #ack_msg = b"CMD_RESULT_SIZE|%s" % len(cmd_result)
    server_ack_msg = sk.recv(100)
    cmd_res_msg = str(server_ack_msg.decode()).split("|")
    print("server response:",cmd_res_msg)
    if cmd_res_msg[0] =="CMD_RESULT_SIZE":
      cmd_res_size = int(cmd_res_msg[1])

      sk.send(b"CLIENT_READY_TO_RECV")
    res = ''
    received_size = 0
    while received_size < cmd_res_size:
      data = sk.recv(500)
      received_size += len(data)
      res += str(data.decode())
    else:
      print(str(res))
      print('-------recv done----')
sk.close()