标签:col process class thread stream from recv stdout 命令
将自己的tcp程序服务端改写成并发
并发服务端
import socket import subprocess from multiprocessing import Process from threading import Thread cmd_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) cmd_socket.bind((‘127.0.0.1‘,8080)) cmd_socket.listen(5) def send_cmd(conn,client_addr): while True: try: cmd = conn.recv(2048) if len(cmd) == 0: break res = subprocess.Popen(cmd.decode(‘utf-8‘), shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) stderr = cmd.stderr.read() stdout = cmd.stdout.read() conn.send(stderr) conn.send(stdout) print(f‘执行{cmd}‘) conn.send(f‘{cmd}执行成功‘.encode(‘utf-8‘)) except Exception: print(client_addr, "连接断开") break conn.close() while True: conn, client_addr = cmd_socket.accept() p = Process(target=send_cmd, args=(conn,)) t = Thread(target=send_cmd, args=(conn,)) p.start() t.start()
客户端
# 客户端 import socket cmd_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) cmd_socket.connect((‘127.0.0.1‘,8080)) while True: cmd = input(‘输入远程操作命令‘) if len(cmd) == 0: continue cmd_socket.send(cmd.encode(‘utf-8‘)) respond = cmd_socket.recv(1024) print(respond.decode(‘utf-8‘)) cmd_socket.close()
标签:col process class thread stream from recv stdout 命令
原文地址:https://www.cnblogs.com/heirenxilou/p/12771746.html