[英]How can I send a message down a websocket running in a thread from tkinter?
我有一個運行的服務器腳本:
async def give_time(websocket,path):
while True:
await websocket.send(str(datetime.datetime.now()))
await asyncio.sleep(3)
start_server = websockets.serve(give_time, '192.168.1.32', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
工作正常,只需每3秒發送一次當前時間。
我可以從運行此代碼的客戶端收到該字符串:
async def hello(): #takes whatever text comes through the websocket and displays it in the socket_text label.
async with websockets.connect('ws://wilsons.lan:8765') as ws:
while True:
text = await ws.recv()
logger.info('message received through websocket:{}'.format(text))
socket_text.configure(text=text) #socket_text is a tkinter object
loop = asyncio.new_event_loop()
def socketstuff():
asyncio.set_event_loop(loop)
asyncio.get_event_loop().run_until_complete(hello())
t = threading.Thread(target=socketstuff,daemon=True)
它在一個線程中運行,以便我可以在主線程中運行tkinter.mainloop
。 這是我用過的第一次threading
,所以我可能會犯錯,但似乎目前的工作。
我需要做的是,能夠根據tkinter事件向websocket發送消息 - 目前只需單擊文本框旁邊的按鈕,但最終會發生更復雜的事情。 點擊部分工作正常。
我發送郵件時遇到了很多麻煩。 我已經嘗試了很多不同的東西,無論是否有async
和await
,盡管這可能只是恐慌。
主要問題似乎是我無法從外部訪問ws
hello()
函數。 這是有道理的,因為我正在使用with
context manager。 但是,如果我只使用ws = websockets.connect('ws://host')
那么我得到一個websockets.py35.client.Connect object
,我嘗試使用send
(或者確實是recv
)方法,我得到了一個object has no attribute 'send'
錯誤。
我希望這是足夠的信息 - 將愉快地發布任何其他要求!
事實證明,解決這個問題的最佳方法是不使用線程。
這篇文章幫我解決了。 它表明你可以在協程中運行tkinter mainloop的一次迭代:
async def do_gui(root,interval=0.05):
while True:
root.update()
await asyncio.sleep(interval)
但是,獲取asyncio.queue
事件以生成websocket消息的最佳方法是使用asyncio.queue
。 創建put_nowait()
回調使用put_nowait()
將一個項添加到隊列中,並且使用與put_nowait()
同時運行的協程,該do_gui
使用await queue.get()
從隊列中獲取消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.