我试图构建的python应用程序面临一个问题:基本上,我有一个脚本,可以从Redis PUBSUB连接接收简单的json数据,我希望将这些数据作为websocket服务器提供给客户端。因此,基本上,每次我从redis连接接收到消息时,都必须使用WebSocket将该消息发送给客户端
这是我的基本代码:
我从redis pubsub连接接收数据的部分:
import json
import redis
redis_url = 'MY-URL'
channel = 'test'
connection = redis.StrictRedis.from_url(redis_url, decode_responses=True)
pubsub = connection.pubsub(ignore_subscribe_messages=False)
pubsub.subscribe(channel)
for item in pubsub.listen():
message = item['data']
if type(message) != int:
message = json.loads(message)
print(message)
这是一个简单的websocket服务器,我使用websockets
:
import asyncio
import websockets
async def main(websocket, path):
while True:
await websockets.send('Some data')
start_server = websockets.serve(main, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
我缺少合并这两部分代码的方法。有没有办法做到这一点
解决方案1
在本例中,我们为每个新的
websocket
连接请求注册新的侦听器解决方案2
在这里,我们使用单列表器向多个客户端发送事件,这些客户端通过websocket注册,并向打开的websocket连接发送消息
相关问题 更多 >
编程相关推荐