WebServer.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. props = f.readlines()
  12. for prop in props:
  13. if prop.startswith("ip"):
  14. ip = prop.split("=")[1].strip()
  15. if prop.startswith("port"):
  16. port = prop.split("=")[1].strip()
  17. async def echo(websocket, path):
  18. global status
  19. try:
  20. async for message in websocket:
  21. logging.info(f"Received message: {message}")
  22. # 将所有的message,写到一个ws.log文件中
  23. with open("ws.log", "a") as f:
  24. f.write(f"{message}\n")
  25. if status != 1:
  26. status = 1
  27. await websocket.send(f"Server says: 你好,服务端收到,连接建立成功")
  28. except websockets.ConnectionClosed as e:
  29. status = 0
  30. logging.warning(f"Connection closed: {e.reason}")
  31. except Exception as e:
  32. status = 0
  33. logging.error(f"Error: {e}", exc_info=True)
  34. async def main():
  35. # SSL context for wss (optional, uncomment if you want to use wss)
  36. # ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  37. # localhost_pem = pathlib.Path(__file__).with_name("localhost.pem")
  38. # ssl_context.load_cert_chain(localhost_pem)
  39. # Remove ssl=ssl_context below if not using wss
  40. async with websockets.serve(echo, ip, port): # , ssl=ssl_context):
  41. await asyncio.Future() # run forever
  42. if __name__ == '__main__':
  43. try:
  44. asyncio.run(main())
  45. except KeyboardInterrupt:
  46. logging.info("Server stopped by KeyboardInterrupt")
  47. except Exception as e:
  48. logging.error(f"Server error: {e}", exc_info=True)