๐ŸŒ WebSockets Implementationยถ

Real-time Ready
Async First
Duck Framework


Duck makes WebSocket implementation simple and powerful ๐Ÿ”Œ.
Forget the boilerplate โ€” with Duck you can add real-time features in just a few lines of code ๐Ÿš€.


โšก Quick Exampleยถ

In your urls.py, define a WebSocket view:

# urls.py

from duck.urls import path
from duck.contrib.websockets import WebSocketView, OpCode

class MyWebSocket(WebSocketView):
    async def on_open(self):
        print("WebSocket connection established")
        
    async def on_receive(self, data: bytes, opcode: int):
        if opcode == OpCode.TEXT:
            message = "You sent " + data.decode("utf-8")
            await self.send_text(message)
        else:
            # Handle binary frames here
            pass

# Register your WebSocket route
urlpatterns = [
    path("/ws/myws", MyWebSocket, name="mywebsocket"),
    # other patterns here.
]

โœ… Thatโ€™s it! Your app is now ready to handle WebSocket connections.


โš™๏ธ Customizing Behaviorยถ

Duckโ€™s WebSocket views support configurable class variables:

  • โฑ RECEIVE_TIMEOUT โ†’ default: 120 seconds
    (timeout before expecting a new frame).

  • ๐Ÿ“ฆ MAX_FRAME_SIZE โ†’ default: 1 * 1024 * 1024 bytes
    (maximum allowed size of a frame).

Simply override these in your WebSocketView subclass to tweak performance.


๐Ÿ’ฌ Practical Examplesยถ

1๏ธโƒฃ Simple Chat Appยถ

A minimal chat implementation that echoes messages back to all connected users.

from duck.contrib.websockets import WebSocketView, OpCode

connected_clients = set()

class ChatSocket(WebSocketView):
    async def on_open(self):
        connected_clients.add(self)
        await self.send_text("๐Ÿ‘‹ Welcome to the chat!")

    async def on_receive(self, data: bytes, opcode: int):
        if opcode == OpCode.TEXT:
            message = data.decode("utf-8")
            # Broadcast to all connected clients
            for client in connected_clients:
                if client != self:
                    await client.send_text(f"User: {message}")

    async def on_close(self):
        connected_clients.remove(self)

2๏ธโƒฃ Live Notificationsยถ

Send server-initiated notifications to clients:

import asyncio
from duck.contrib.websockets import WebSocketView
from duck.utils.asyncio import create_task # Better than default asyncio.create_task

class NotificationSocket(WebSocketView):
    async def on_open(self):
        # Push notifications every 5 seconds
        create_task(self.push_notifications())

    async def push_notifications(self):
        count = 0
        while True:
            await asyncio.sleep(5)
            count += 1
            await self.send_text(f"๐Ÿ”” Notification #{count}")

โœจ With Duckโ€™s WebSocket support, you can build chat apps, live dashboards, multiplayer games, IoT streams, and more โ€” all with async-native performance ๐ŸŒโšก


๐Ÿ‘‰ Next: Learn how async fits into the bigger picture with โšก ASGI or see how it plays with ๐Ÿ–ฅ๏ธ WSGI.