首页 > 解决方案 > 如何让 WebSocket 服务器/客户端与两方通信

问题描述

我在这里寻求帮助,因为我真的不知道该怎么做。

我想用 websocket 做到这一点:

在此处输入图像描述

我已经有了我的前端和 ImageAnalyser。ImageAnalyser 是一个 WebSocket 服务器。

在这种状态下,我的后端(python)必须同时作为服务器客户端。但是我没有发现任何东西可以使这种同步化成为可能。

我查看了 asyncio 和 websockets,但没有成功。任何人都可以帮助我吗?事实是我需要“位置”等待“功能”,但它就像一个内部服务器正在等待一个内部客户端,我不知道这是否可能。

谢谢

标签: pythonwebsocketpython-asyncio

解决方案


我是这样做的。我不知道这是否是一个好方法,但它确实有效。

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()

推荐阅读