【发布时间】:2019-07-31 23:07:58
【问题描述】:
我搭建了一个websocket服务器,简化版如下图:
import websockets, subprocess, asyncio, json, re, os, sys
from multiprocessing import Process
def docker_command(command_words):
return subprocess.Popen(
["docker"] + command_words,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
async def check_submission(websocket:object, submission:dict):
exercise=submission["exercise"]
with docker_command(["exec", "-w", "badkan", "grade_exercise", exercise]) as proc:
for line in proc.stdout:
print("> " + line)
await websocket.send(line)
async def run(websocket, path):
submission_json = await websocket.recv() # returns a string
submission = json.loads(submission_json) # converts the string to a python dict
####
await check_submission(websocket, submission)
websocketserver = websockets.server.serve(run, '0.0.0.0', 8888, origins=None)
asyncio.get_event_loop().run_until_complete(websocketserver)
asyncio.get_event_loop().run_forever()
当一次只有一个用户时,它可以正常工作。但是,当多个用户尝试使用服务器时,服务器会依次处理它们,因此以后的用户必须等待很长时间。
我尝试将标有“####”(“await check_submission...”)的行替换为:
p = Process(target=check_submission, args=(websocket, submission,))
p.start()
但是,它不起作用 - 我收到了运行时警告:“coroutine: 'check_submission' is never awaited”,并且我没有看到任何通过 websocket 的输出。
我还尝试将这些行替换为:
loop = asyncio.get_event_loop()
loop.set_default_executor(ProcessPoolExecutor())
await loop.run_in_executor(None, check_submission, websocket, submission)
但得到一个不同的错误:“can't pickle asyncio.Future objects”。
如何构建这个多处理 websocket 服务器?
【问题讨论】:
标签: python-3.x websocket async-await python-multiprocessing python-asyncio