我已经坚持了一段时间,希望有人能有所了解!
我想在浏览器中的JavaScript和Python函数(当前使用网络密码模块)之间建立一个网络平台连接。
Python 函数应始终用于浏览器发送的消息listen()
有时我想从外部脚本或函数向浏览器发送消息,例如通过调用函数speak()
这是我目前的代码:
listen
async def listen(self, websocket, path):
while True:
need_update = await websocket.recv()
print(f'< {need_update}')
start_server = websockets.serve(listen(), 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
speak
async def speak(data):
async with websockets.connect('ws://localhost:8765') as websocket:
await websocket.send(data)
print(f'> {data}')
asyncio.get_event_loop().run_until_complete(speak(input("? ")))
使用此方法,该函数只会将消息发送到 Python 函数,JavaScript 代码不会收到任何内容。speaklisten
相反,我可以同时启动这两个函数,但不能从外部函数调用。asyncio.gather(...)speak
真的不知道如何解决这个问题。
一只甜甜圈
相关分类