[英]Python UDP and Websockets together
我正在處理一個應用程序。 在哪里使用python websockets。 現在,我需要異步運行並在不同端口上偵聽的UDP和WS。
我無法執行此操作,因為WS recv()無限期等待,直到收到消息為止。 消息將被接收並推入隊列。 我需要UDP才能接收並推送到同一隊列。 下面的此類僅實現websocket。 我需要另一個帶有UDP的類,並且兩個類實例均異步運行。
import websockets
import json
from sinric.command.mainqueue import queue
from sinric.callback_handler.cbhandler
import CallBackHandler
from time import sleep
class SinricProSocket:
def __init__(self, apiKey, deviceId, callbacks):
self.apiKey = apiKey
self.deviceIds = deviceId
self.connection = None
self.callbacks = callbacks
self.callbackHandler = CallBackHandler(self.callbacks)
pass
async def connect(self): # Producer
self.connection = await websockets.client.connect('ws://2.5.2.2:301',
extra_headers={'Authorization': self.apiKey,
'deviceids': self.deviceIds},
ping_interval=30000, ping_timeout=10000)
if self.connection.open:
print('Client Connected')
return self.connection
async def sendMessage(self, message):
await self.connection.send(message)
async def receiveMessage(self, connection):
try:
message = await connection.recv()
queue.put(json.loads(message))
except websockets.exceptions.ConnectionClosed:
print('Connection with server closed')
async def handle(self):
# sleep(6)
while queue.qsize() > 0:
await self.callbackHandler.handleCallBacks(queue.get(), self.connection)
return
感謝您在評論中的時間。 我通過在2個不同的守護程序線程中運行WS和UDP實例解決了此問題。
解決此問題的一種好方法是使用線程。 您可以接受一條消息並將其放入隊列,然后在其他線程上處理該隊列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.