我正在尝试制作一个程序,使许多web套接字连接到我创建的服务器:
class WebSocketClient():
@asyncio.coroutine
def run(self):
print(self.client_id, 'Connecting')
ws = yield from aiohttp.ws_connect(self.url)
print(self.client_id, 'Connected')
print(self.client_id, 'Sending the message')
ws.send_str(self.make_new_message())
while not ws.closed:
msg = yield from ws.receive()
if msg.tp == aiohttp.MsgType.text:
print(self.client_id, 'Received the echo')
yield from ws.close()
break
print(self.client_id, 'Closed')
@asyncio.coroutine
def make_clients():
for client_id in range(args.clients):
yield from WebSocketClient(client_id, WS_CHANNEL_URL.format(client_id=client_id)).run()
event_loop.run_until_complete(make_clients())
问题是所有的客户都在一个接一个地完成他们的工作:
^{pr2}$我尝试过使用^{
我应该采用什么方法来实现这一点?在
使用asyncio.wait是一个很好的方法。您可以将其与asyncio.ensure_future和asyncio.sleep组合以逐步创建任务:
EDIT:我实现了一个
^{pr2}$FutureSet
类,它应该做你想要的。这个集合可以填充futures并在完成后自动删除它们。也可以等待所有的未来完成。在示例:
相关问题 更多 >
编程相关推荐