我正在编写处理两个WebSocket的函数,每个WebSocket的响应将改变共享的DataFrame df。
import json
import asyncio
import websockets
@asyncio.coroutine
def printResponse(df, dataSocket, quoteSocket, dataRequest, quoteRequest):
yield from dataSocket.send(dataRequest)
yield from quoteSocket.send(quoteRequest)
response = yield from dataSocket.recv() # skip first response
response = yield from quoteSocket.recv() # skip first response
while True:
response = yield from dataSocket.recv()
print("<< {}".format(json.loads(response)))
df = changeRecord(df, response)
response = yield from quoteSocket.recv()
print("<< {}".format(json.loads(response)))
df = changeRecord(df, response)
我不确定但是当前代码似乎依次处理两个WebSockets。我希望以先出先后的方式处理响应&#34;方式,无论它来自哪个WebSocket。我应该如何进行更改以实现这一目标?
答案 0 :(得分:1)
因为您在同一个while循环中使用了两个dataSocket
语句,所以它会按顺序处理它们,然后无限重复。
因此,它会一直等到quoteSocket
得到回复,然后等待它从Tasks()
得到回复,然后冲洗并重复。
import json
import asyncio
import websockets
@asyncio.coroutine
def coroutine_1(df, dataSocket):
yield from dataSocket.send(dataRequest)
response = yield from dataSocket.recv() # skip first response
while True:
response = yield from dataSocket.recv()
print("<< {}".format(json.loads(response)))
df = changeRecord(df, response)
@asyncio.coroutine
def coroutine_2(df, quoteSocket):
yield from quoteSocket.send(quoteRequest)
response = yield from quoteSocket.recv() # skip first response
while True:
response = yield from quoteSocket.recv()
print("<< {}".format(json.loads(response)))
df = changeRecord(df, response)
@asyncio.coroutine
def printResponse(df, dataSocket, quoteSocket):
websocket_task_1 = asyncio.ensure_future(coroutine_1(df, dataSocket))
websocket_task_2 = asyncio.ensure_future(coroutine_2(df, quoteSocket))
yield from asyncio.wait([websocket_task_1, websocket_task_2])
适用于您正在尝试执行的操作,因为它们允许协同程序彼此独立运行。因此,如果你在他们自己的Task包装器中启动两个单独的协同程序,那么每个协同程序将等待他们自己的下一个响应,而不必打扰另一个。
例如:
{{1}}