Browse Source

Merge pull request #2432 from zauberzeug/websockets

Add example on how to use websockets library
Falko Schindler 1 year ago
parent
commit
bdb448d0ae
3 changed files with 51 additions and 0 deletions
  1. 49 0
      examples/websockets/main.py
  2. 1 0
      examples/websockets/requirements.txt
  3. 1 0
      website/examples.py

+ 49 - 0
examples/websockets/main.py

@@ -0,0 +1,49 @@
+#!/usr/bin/env python3
+"""Websockets example showing messages from connected clients and broadcasting via button click.
+
+NOTE: NiceGUI already handles all the communication for you, so you don't need to worry about websockets and the like normally.
+This example is only for advanced use cases where you want to allow other, non-NiceGUI clients to connect to your server.
+"""
+import asyncio
+from typing import Set
+
+import websockets
+from websockets.server import WebSocketServerProtocol
+
+from nicegui import app, ui
+
+CONNECTIONS: Set[WebSocketServerProtocol] = set()
+
+ui.label('Websockets demo').classes('text-2xl')
+ui.label('Run this in the console to connect:')
+ui.code('python -m websockets ws://localhost:8765/').classes('pr-8 pt-1 h-12')
+with ui.row().classes('items-center'):
+    connections_label = ui.label('0')
+    ui.label('connections')
+    ui.button('send hello', on_click=lambda: websockets.broadcast(CONNECTIONS, 'Hello!')).props('flat')
+ui.separator().classes('mt-6')
+ui.label('incoming messages:')
+messages = ui.column().classes('ml-4')
+
+
+async def handle_connect(websocket: WebSocketServerProtocol):
+    """Register the new websocket connection, handle incoming messages and remove the connection when it is closed."""
+    try:
+        CONNECTIONS.add(websocket)
+        connections_label.text = len(CONNECTIONS)
+        async for data in websocket:
+            with messages:
+                ui.label(str(data))
+    finally:
+        CONNECTIONS.remove(websocket)
+        connections_label.text = len(CONNECTIONS)
+
+
+async def start_websocket_server():
+    async with websockets.serve(handle_connect, 'localhost', 8765):
+        await asyncio.Future()
+
+# start the websocket server when NiceGUI server starts
+app.on_startup(start_websocket_server)
+
+ui.run()

+ 1 - 0
examples/websockets/requirements.txt

@@ -0,0 +1 @@
+websockets >= 12.0

+ 1 - 0
website/examples.py

@@ -61,4 +61,5 @@ examples: List[Example] = [
     Example('FullCalendar', 'show an interactive calendar using the [FullCalendar library](https://fullcalendar.io/)'),
     Example('FullCalendar', 'show an interactive calendar using the [FullCalendar library](https://fullcalendar.io/)'),
     Example('Pytest', 'test a NiceGUI app with pytest'),
     Example('Pytest', 'test a NiceGUI app with pytest'),
     Example('Pyserial', 'communicate with a serial device'),
     Example('Pyserial', 'communicate with a serial device'),
+    Example('Websockets', 'use [websockets library](https://websockets.readthedocs.io/) to start a websocket server'),
 ]
 ]