WebServer.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import asyncio
  2. import websockets
  3. import logging
  4. # Initialize logging
  5. logging.basicConfig(level=logging.INFO)
  6. ip = "192.168.137.1"
  7. port = 9999
  8. status = 0 # 1连接 0失败
  9. # 从同目录下读取props.properties文件,获取配置(ip、port)信息
  10. with open("props.properties", "r") as f:
  11. global ip, port
  12. props = f.readlines()
  13. for prop in props:
  14. if prop.startswith("ip"):
  15. ip = prop.split("=")[1].strip()
  16. if prop.startswith("port"):
  17. port = prop.split("=")[1].strip()
  18. async def echo(websocket, path):
  19. global status
  20. try:
  21. async for message in websocket:
  22. logging.info(f"Received message: {message}")
  23. # 将所有的message,写到一个ws.log文件中
  24. with open("ws.log", "a") as f:
  25. f.write(f"{message}\n")
  26. if status != 1:
  27. status = 1
  28. await websocket.send(f"Server says: 你好,服务端收到,连接建立成功")
  29. except websockets.ConnectionClosed as e:
  30. status = 0
  31. logging.warning(f"Connection closed: {e.reason}")
  32. except Exception as e:
  33. status = 0
  34. logging.error(f"Error: {e}", exc_info=True)
  35. async def main():
  36. # SSL context for wss (optional, uncomment if you want to use wss)
  37. # ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  38. # localhost_pem = pathlib.Path(__file__).with_name("localhost.pem")
  39. # ssl_context.load_cert_chain(localhost_pem)
  40. # Remove ssl=ssl_context below if not using wss
  41. async with websockets.serve(echo, ip, port): # , ssl=ssl_context):
  42. await asyncio.Future() # run forever
  43. if __name__ == '__main__':
  44. try:
  45. asyncio.run(main())
  46. except KeyboardInterrupt:
  47. logging.info("Server stopped by KeyboardInterrupt")
  48. except Exception as e:
  49. logging.error(f"Server error: {e}", exc_info=True)