【发布时间】:2016-01-15 07:24:34
【问题描述】:
我正在尝试编写一个程序来与我创建的服务器建立大量网络套接字连接:
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())
问题是所有的客户都是一个接一个地工作:
0 Connecting
0 Connected
0 Sending the message
0 Received the echo
0 Closed
1 Connecting
1 Connected
1 Sending the message
1 Received the echo
1 Closed
...
我尝试使用asyncio.wait,但所有客户端都是一起启动的。我希望它们逐渐创建并在每个创建后立即连接到服务器。同时继续创建新客户。
我应该采用什么方法来实现这一点?
【问题讨论】:
-
请把WebSocketClient装饰成
@coroutine -
@AndrewSvetlov 是的,它被装饰了——复制/粘贴错误
-
@J.F.Sebastian 谢谢,我会调查的
标签: python python-3.x python-asyncio aiohttp