【发布时间】:2018-09-06 08:21:21
【问题描述】:
我是 python 新手,我必须创建一个程序来保持从 web socket 和 pipe 进行 linsting,所以我需要两个异步函数。
这些函数中的每一个都在不同的线程中调用其他方法来详细说明接收到的 json 的内容。
即我在套接字线程上收到一条消息,我收到消息并抛出一个新线程来详细说明消息。
这是实际的代码:
import asyncio
import sys
import json
import websockets
# Keep listening from web socket and pipe
async def socket_receiver():
"""Listening from web socket"""
file_socket = open(r"SocketReceived.txt", "w")
header = {"Authorization": r"Basic XXXXXXXXXXXXXX="}
async with websockets.connect(
'wss://XXXXXXXXX', extra_headers=header) as web_socket:
print("SOCKET receiving:")
greeting = await web_socket.recv()
json_message = json.loads(greeting)
file_socket.write(json_message)
print(json_message)
file_socket.close()
async def pipe_receiver():
"""Listening from pipe"""
file_pipe = open(r"ipeReceived.txt", "w")
while True:
print("PIPE receiving:")
line = sys.stdin.readline()
if not line:
break
jsonObj = json.loads(line);
file_pipe.write(jsonObj['prova'] + '\n')
# jsonValue = json.dump(str(line), file);
sys.stdout.flush()
file_pipe.close()
asyncio.get_event_loop().run_until_complete(socket_receiver())
asyncio.get_event_loop().run_until_complete(pipe_receiver())
run_until_complete 方法在我的情况下永远保留(它等待函数结束),所以只有套接字启动。
我怎样才能同时开始?谢谢
【问题讨论】:
-
Asyncio two loops for different I/O tasks? 可能重复 - 这有帮助吗?
-
我更喜欢更清晰的解决方案,因为我有这两种监听方法,但每个收到的消息都会抛出一个新线程,我只是在看线程池
标签: python python-3.x multithreading python-asyncio