๐ WebSockets Implementationยถ
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:120seconds
(timeout before expecting a new frame).๐ฆ
MAX_FRAME_SIZEโ default:1 * 1024 * 1024bytes
(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.