123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import asyncio
- import websockets
- import logging
- logging.basicConfig(level=logging.INFO)
- ip = "192.168.137.1"
- port = 9999
- status = 0
- with open("props.properties", "r") as f:
- global ip, port
- props = f.readlines()
- for prop in props:
- if prop.startswith("ip"):
- ip = prop.split("=")[1].strip()
- if prop.startswith("port"):
- port = prop.split("=")[1].strip()
- async def echo(websocket, path):
- global status
- try:
- async for message in websocket:
- logging.info(f"Received message: {message}")
-
- with open("ws.log", "a") as f:
- f.write(f"{message}\n")
- if status != 1:
- status = 1
- await websocket.send(f"Server says: 你好,服务端收到,连接建立成功")
- except websockets.ConnectionClosed as e:
- status = 0
- logging.warning(f"Connection closed: {e.reason}")
- except Exception as e:
- status = 0
- logging.error(f"Error: {e}", exc_info=True)
- async def main():
-
-
-
-
-
- async with websockets.serve(echo, ip, port):
- await asyncio.Future()
- if __name__ == '__main__':
- try:
- asyncio.run(main())
- except KeyboardInterrupt:
- logging.info("Server stopped by KeyboardInterrupt")
- except Exception as e:
- logging.error(f"Server error: {e}", exc_info=True)
|