我正在尝试在客户端和服务器(python)之间创建单向websocket连接。我目前使用的原型库是websockets和simplesocketserver。我有一个从服务器到客户端的世界示例,但是我需要能够在不提示客户端的情况下将数据从后端发送到客户端。所有的websockets示例似乎都显示服务器在侦听客户端然后进行响应。
到目前为止,我已经尝试过:
使用websockets 8.0,无提示地将数据从服务器发送到客户端,但这仅适用于硬编码的字符串,我不明白如何从客户端无提示地按需发送真实数据
以相同的方式使用simplesocketserver
来自websockets文档的示例:
import asyncio
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
start_server = websockets.serve(hello, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
注意:单向通信的需要是由于现有体系结构。
关于此的任何指导或资源都很好,我希望我能忽略一些简单的事情。谢谢!
我遇到了类似的问题。经过一番周折,我找到了一个对我有用的解决方案,也许对您也适用。我已经在Linux以及Firefox和移动Safari(并行)上对此进行了测试。
InputThread
等待命令行上的输入(单词)并将它们写入列表,每当附加新字符串或连接客户端时,该列表就会发送给所有连接的客户端。
最好的问候,菲利普
代码段
import asyncio
import websockets
import json
from threading import Thread
words = []
clients = []
async def register_client(websocket, path):
# register new client in list and keep connection open
clients.append(websocket)
await send_to_all_clients()
while True:
await asyncio.sleep(10)
async def send_to_all_clients():
global words
for i, ws in list(enumerate(clients))[::-1]:
try:
await ws.send(json.dumps({"words": words}))
except websockets.exceptions.ConnectionClosedError:
# remove if connection closed
del clients[i]
class InputThread(Thread):
def run(self):
global words
async def sending_loop():
while True:
i = input()
if not i.strip():
continue
words.append({"options": [i.strip()]})
await send_to_all_clients()
asyncio.run(sending_loop())
InputThread().start()
asyncio.get_event_loop().run_until_complete(
websockets.serve(register_client, "localhost", 8765))
asyncio.get_event_loop().run_forever()