Standard HTTP operates on a request-response cycle: the client asks, the server replies, and the socket closes. Real-time web features — such as live group chat, instant multiplayer collaboration, stock tickers, and notification alerts — require persistent, full-duplex WebSockets via Django Channels.
# Install Channels with Redis support
pip install channels channels_redis daphne
# mywebsite/settings.py
INSTALLED_APPS = [
'daphne', # Must be at the very top of INSTALLED_APPS!
'django.contrib.admin',
# ...
'channels',
'chat',
]
ASGI_APPLICATION = 'mywebsite.asgi.application'
# Channel Layer backed by Redis
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# chat/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatRoomConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f"chat_{self.room_name}"
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
"""Receive message from client WebSocket."""
data = json.loads(text_data)
message = data['message']
username = self.scope['user'].username or "Anonymous"
# Broadcast message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message_broadcast',
'message': message,
'username': username
}
)
async def chat_message_broadcast(self, event):
"""Send message down to WebSocket socket."""
await self.send(text_data=json.dumps({
'message': event['message'],
'username': event['username']
}))
Broaden your backend architecture, REST API design, and production engineering expertise:
Understand ASGI vs WSGI architectures for asynchronous protocols.
Receive WebSocket events directly in the frontend using HTMX-ws.
Broadcast real-time task progress notifications over WebSockets.
Deploy ASGI applications with Uvicorn and Nginx WebSocket proxying.