Step-by-Step Instructions
Step 1: Configure ASGI Application
- Open the
asgi.pyfile in the project directory (chat_project/asgi.py). - Modify it to include WebSocket support using
URLRouter:
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from chat.routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chat_project.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
Step 2: Create Routing for WebSockets
- In the
chatapp, create arouting.pyfile:
touch chat/routing.py
Add the WebSocket URL patterns:
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/chat/<str:room_name>/', consumers.ChatConsumer.as_asgi()),
]
Step 3: Create a WebSocket Consumer
- In the
chatapp, create aconsumers.pyfile:
touch chat/consumers.py
Add a consumer class to handle WebSocket connections:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(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 the chat group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave the chat group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send the message to the group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
async def chat_message(self, event):
message = event['message']
# Send the message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
Run the Development Server Start the server to verify everything works:
python manage.py runserver