python学习40——课后练习
Posted python小小人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习40——课后练习相关的知识,希望对你有一定的参考价值。
将自己的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()
以上是关于python学习40——课后练习的主要内容,如果未能解决你的问题,请参考以下文章