Django

⌘K
  1. Home
  2. Django
  3. chat
  4. User To User Chat
  5. Part 3: Setting Up Channels

Part 3: Setting Up Channels

Step-by-Step Instructions


Step 1: Configure ASGI Application

  1. Open the asgi.py file in the project directory (chat_project/asgi.py).
  2. 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

  1. In the chat app, create a routing.py file:
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

  1. In the chat app, create a consumers.py file:
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

How can we help?