main.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python
  2. """Websockets example showing messages from connected clients and broadcasting via button click.
  3. NOTE: NiceGUI already handles all the communication for you so you don't need to worry about websockets and the like normally.
  4. This example is only for advanced use cases where you want to allow other, non-NiceGUI clients to connect to your server.
  5. """
  6. import asyncio
  7. from typing import Set
  8. import websockets
  9. from websockets.server import WebSocketServerProtocol
  10. from nicegui import app, ui
  11. CONNECTIONS: Set[WebSocketServerProtocol] = set()
  12. ui.label('Websockets demo').classes('text-2xl')
  13. ui.label('Run this in the console to connect:')
  14. ui.code('python -m websockets ws://localhost:8765/').classes('pr-8 pt-1 h-12')
  15. with ui.row().classes('items-center'):
  16. connections_label = ui.label('0')
  17. ui.label('connections')
  18. ui.button('send hello', on_click=lambda: websockets.broadcast(CONNECTIONS, 'Hello!')).props('flat')
  19. ui.separator().classes('mt-6')
  20. ui.label('incoming messages:')
  21. messages = ui.column().classes('ml-4')
  22. async def handle_connect(websocket: WebSocketServerProtocol):
  23. '''Register the new websocket connection, handle incoming messages and remove the connection when it is closed.'''
  24. try:
  25. CONNECTIONS.add(websocket)
  26. connections_label.text = len(CONNECTIONS)
  27. async for data in websocket:
  28. with messages:
  29. ui.label(str(data))
  30. finally:
  31. CONNECTIONS.remove(websocket)
  32. connections_label.text = len(CONNECTIONS)
  33. async def start_websocket_server():
  34. async with websockets.serve(handle_connect, "localhost", 8765):
  35. await asyncio.Future()
  36. # start the websocket server when NiceGUI server starts
  37. app.on_startup(start_websocket_server)
  38. ui.run()