我正在嘗試將 web-socket 功能(以回應一些偶爾的基于 web-socket 的入站請求)添加到已經在做其他事情的現有小型 python 桌面應用程式中。它已經有幾個執行緒正在運行執行各種任務。
我在這里找到并查看了一些與我的問題相似的 STACK 文章,遺憾的是,我對 python 中的 async 非常陌生。我無法根據其他文章創建解決方案。
這是其中一篇類似的文章: Asyncio websocket in separate thread
我無法得到這樣的解決方案來為我作業。
這是我失敗的簡單代碼:
# asamp.py
import time
import datetime
import asyncio
import websockets
import threading
def bgWorker_SK():
# create handler for each connection
async def handler(websocket, path):
data = await websocket.recv()
reply = f"Data recieved as: {data}!"
await websocket.send(reply)
start_server = websockets.serve(handler, "localhost", 5564)
asyncio.loop.run_until_complete(start_server)
asyncio.loop.run_forever()
bgsk = threading.Thread(target=bgWorker_SK, daemon=True).start()
if __name__ == '__main__':
# the main is off busy doing something other work...
# trivial example here
while True:
print (datetime.datetime.now())
time.sleep(2)
以上,在 Python 3.8.10 中生成錯誤:
builtins.RuntimeError:執行緒 'Thread-1' 中沒有當前事件回圈。
請幫忙 :-{
uj5u.com熱心網友回復:
嘗試:
# asamp.py
import time
import datetime
import asyncio
import websockets
import threading
def bgWorker_SK():
# create handler for each connection
async def handler(websocket, path):
data = await websocket.recv()
reply = f"Data recieved as: {data}!"
await websocket.send(reply)
loop = asyncio.new_event_loop() # <-- create new loop in this thread here
asyncio.set_event_loop(loop)
start_server = websockets.serve(handler, "localhost", 5564)
loop.run_until_complete(start_server)
loop.run_forever()
bgsk = threading.Thread(target=bgWorker_SK, daemon=True).start()
if __name__ == "__main__":
# the main is off busy doing something other work...
# trivial example here
while True:
print(datetime.datetime.now())
time.sleep(2)
這會打開新的 TCP 埠localhost:5564并開始監聽它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/489301.html
標籤:python-3.x 网络套接字 蟒蛇异步
