所以我试图将我的连接分成两个线程: A - 一个用于向后端发送 json。 B - 一个用于从后端接收消息。
想法是能够在 for 循环中运行第一个以创建多个 json,但是我不能让“while true”语句继续在与循环相同的线程中接收消息而从不重复。
代码的简化版本如下所示:
async def send_json(study_info):
'''
Starts the websocket connection. Then sends the need information to the back end
'''
async with websockets.connect('ws://localhost:1234') as websocket:
study_info_dict = dict(study_info[0])
msg = json.dumps({'type': 'add_to_queue', 'body': {
'eln_no': study_info_dict["ELN"],
'eln_info': study_info,
'user': study_info_dict["Owner"]
}})
await websocket.send(msg)
print("> {}".format(msg))
async def recieve_messages():
async with websockets.connect('ws://localhost:1234') as websocket:
while True:
greeting = await websocket.recv()
print("< {}".format(greeting))
#if greeting["type"] == "update"
def main():
threading.Thread(
target=thread_async_combiner_message,
args=(),
daemon=True,
).start()
# Execute frontend of program logic
threading.Thread(
target=thread_async_combiner_frontend, args=(window, eln_no), daemon=True
).start()
我不想把它全部放在那里,因为有很多,这就是我遇到问题的地方。
代码现在可以正常工作,因为我可以发送消息,但我没有收到任何消息,因为后端只会将消息发送给发送消息的同一个客户端(这应该是这样)。
我尝试在启动两个线程并将连接作为变量之前启动 while websocket.connect,但是一旦创建了两个线程,连接就会关闭。 我明白为什么会这样,但我希望能就如何最好地处理这个问题提供一些意见