python - 如何让 WebSocket 服务器/客户端与两方通信
问题描述
我在这里寻求帮助,因为我真的不知道该怎么做。
我想用 websocket 做到这一点:
我已经有了我的前端和 ImageAnalyser。ImageAnalyser 是一个 WebSocket 服务器。
在这种状态下,我的后端(python)必须同时作为服务器客户端。但是我没有发现任何东西可以使这种同步化成为可能。
我查看了 asyncio 和 websockets,但没有成功。任何人都可以帮助我吗?事实是我需要“位置”等待“功能”,但它就像一个内部服务器正在等待一个内部客户端,我不知道这是否可能。
谢谢
解决方案
我是这样做的。我不知道这是否是一个好方法,但它确实有效。
class Session:
# A session is a client for the FeatureExtractor, and a server for the Front-End.
def __init__(self, host: str, port: int, openFaceUri: str):
# Serving the front-end.
self.server = websockets.serve(self.main_server, host, port)
# Asking OpenFace
self.openFaceUri = openFaceUri
self.ws = None
# Image, features of the image. Note that features couldn't be associated to image through time.
self.img, self.features = None, None
# Flags for synchronization between client and server.
self.newImgRcvd = asyncio.Event()
self.workDone = asyncio.Event()
# Model
#self.model = Modelization()
#self.model.open().feature_engineering().create_model().train_model()
# Methods
def start(self):
asyncio.get_event_loop().run_until_complete(self.server)
asyncio.get_event_loop().run_until_complete(self.main_client())
#asyncio.get_event_loop().run_forever()
###################################################################
# For client. Keep connection open with OpenFace.
async def __async__connect(self):
'''
Keep a connection alive between the FeatureExtractor (Openface) and here.
'''
print("Attempting connection to {}".format(self.openFaceUri))
# perform async connect, and store the connected WebSocketClientProtocol
# object, for later reuse for send & recv
self.ws = await websockets.connect(self.openFaceUri)
print("Connected to Openface \n")
async def send_image_to_feature_extractor(self):
while True:
await self.newImgRcvd.wait()
self.newImgRcvd.clear()
await self.ws.send(self.img)
self.features = await self.ws.recv()
self.workDone.set()
async def main_client(self):
await self.__async__connect()
await self.send_image_to_feature_extractor()
############################### Server ####################################
async def main_server(self, websocket, path):
while True:
self.img = await websocket.recv()
self.newImgRcvd.set()
await self.workDone.wait()
self.workDone.clear()
await websocket.send(self.features)
srv = Session(host="localhost", port=8765, openFaceUri="ws://localhost:8080")
srv.start()
推荐阅读
- multi-level - 如何在 R 中使用 glmmpql 在多级准泊松中获得稳健的标准误差
- angular - 如果它是一个接口,如何通过 Angular DI 注入 ActivatedRoute?
- elasticsearch - 具有源过滤的弹性搜索搜索忽略排除
- reactjs - 道具未定义,但我可以看到它在控制台记录道具
- asp.net - jwt 验证期间的 Asp.net 核心缓存 jwk
- sql - 使用集群的 hive 子查询优化
- r - 如何为股票代码列表上的调整收盘价编写一个 for 循环?
- reactjs - React-router - 将当前路由设置为最后一个路由
- javascript - Firebase 函数 - admin.messaging().sendToTopic 执行但从未进入 `then` 块
- ios - Xcode 中的 IOS MapKit 出错:在捆绑包 NSBundle 中找不到名为“Main”的故事板