Web socket protocol was standardized in 2011 and all modern browsers provide built-in support for it. It establishes the tunnel between the server and the client. (Publisher and Subscriber)
Because Django does not have a default support for WebSocket, we need to use a third-party library, the Django Channels, built on ASGI specification.
An extension for Django projects, Django Channels adds the functionality of asynchronous code underneath and through Django's synchronous core, allowing Django projects to handle not only HTTP, but protocols that require long-running connections such as WebSockets, MQTT, chatbots, and etc.
Django Channels effectively integrates with DJango's auth systems, session system, and more.
A scope contains information about the path of connection, IP address, headers, and content data. The life cycle of scope is illustrated below:
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Trhead, ChatMessage
class ChatConsumer(AsyncConsumer):
async def websocket_onnect(self, event):
print("connected", event)
async def websocket_receive(self, event):
// when a message is received from the websocket
async def websocket_disconnect(self, event):
// when the socket disconnects
You are not overriding regular HTTP methods.
Because websocket is a different protocol than HTTP, so you can open up both websocket and HTTP communications.
To connect different users even on the same computer or different computers, we need to have a data store of events that are happening. To do this, you must install Redis, which is a messaging queue for events that happen. Then Channels consume these events from Redis.