From debc511312bb7669ab129cd87453aa37ce641df6 Mon Sep 17 00:00:00 2001 From: wsy182 <2392948297@qq.com> Date: Mon, 1 Jun 2026 21:33:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=9D=E5=AD=98=E5=BD=93=E5=89=8D=E6=9B=B4?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- handle_client.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 handle_client.py diff --git a/handle_client.py b/handle_client.py new file mode 100644 index 0000000..2d4e114 --- /dev/null +++ b/handle_client.py @@ -0,0 +1,61 @@ +import asyncio +import websockets +import cv2 +import numpy as np +from loguru import logger + + +async def handle_client(websocket): + client = websocket.remote_address + logger.info(f"Client connected: {client}") + + frame_count = 0 + + try: + async for message in websocket: + frame_count += 1 + + data = np.frombuffer(message, dtype=np.uint8) + frame = cv2.imdecode(data, cv2.IMREAD_COLOR) + + if frame is None: + logger.warning(f"Decode frame failed from client={client}") + continue + + if frame_count % 100 == 0: + logger.info(f"Received frames={frame_count}, client={client}, size={len(message)} bytes") + + cv2.imshow("Android Camera", frame) + + if cv2.waitKey(1) & 0xFF == 27: + logger.info("ESC pressed, closing display") + break + + except websockets.ConnectionClosed: + logger.info(f"Client disconnected: {client}") + + except Exception as e: + logger.exception(f"WebSocket error, client={client}, error={e}") + + finally: + logger.info(f"Connection closed: client={client}, total_frames={frame_count}") + cv2.destroyAllWindows() + + +async def main(): + host = "0.0.0.0" + port = 8765 + + logger.info(f"WebSocket server started: ws://{host}:{port}") + + async with websockets.serve( + handle_client, + host, + port, + max_size=10 * 1024 * 1024 + ): + await asyncio.Future() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file