Django Channels and WebSockets enable real-time features like chat, live notifications, and collaborative apps. They allow persistent, asynchronous connections between clients and servers.
Channels uses ASGI instead of WSGI and supports long-lived connections using async consumers.
# Install Django Channels package
pip install channels
# Daphne is the ASGI server for Channels
pip install daphne
# Add channels and define ASGI application
INSTALLED_APPS = [
'channels',
]
ASGI_APPLICATION = 'myproject.asgi.application'
# Route HTTP and WebSocket protocols
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import myapp.routing
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(myapp.routing.websocket_urlpatterns)
),
})
# Async consumer for chat messages
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
async def receive(self, text_data):
await self.send(text_data=text_data)
# WebSocket URL routing
from django.urls import re_path
from .consumers import ChatConsumer
websocket_urlpatterns = [
re_path(r'ws/chat/', ChatConsumer.as_asgi()),
]
Messages sent by one client are instantly broadcast to all connected users using Redis-powered channel layers.
Client → WebSocket → Consumer → Channel Layer → Broadcast → Clients
Test the concept: Send a message below. The JS script acts as the "Server" and echoes it back.