Channels

Channels is the new concept in Django framework. Channels uses WebSockets to enable two-way communication between the server and client. Django is synchronous and Channels provide asynchronous request by websockets . channels are mostly used as sending email,notification and building a chat application

consumers

Channels works on redis server which is in-memory. Channels work as message broker which all messages are stored in Queue(first in first out). there are consumers and workers . messages are add to AsgiHandler and connect to the other ends and broadcast the message.

Message

Message objects are what consumers get passed as their only argument. They encapsulate the basic ASGI message, which is a dict, with extra information.

Groups

Groups are the core concept of channels . Group provide multi-cast messaging. Instead of echoing the message back to the client, we’ll instead send it to the whole Group, which means any client who’s been added to it will get the message.

Lets code

Installation
pip install -U channels
After installing channels , add channels app in your settings file.
Installed_apps={
	app ,
	.
	.
    channels, 
}

And now add a below code in app/consumers.py .

from channels import Channel
from channels import Group 


def ws_add(message):
    Group("chat").add(message.reply_channel)
create new routing file in the same folder where settings file . It is same as urls.py in django app.
from channels.routing import route
from chat.consumers import ws_add

channel_routing = [ 
			route("websocket.connect", ws_add),
		]
And last add channel_layer code in settings.py
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgiref.inmemory.ChannelLayer",
        "ROUTING": "myproject.routing.channel_routing",
    },
}
And now go to your terminal and run your server
python manage.py runserver 
Go to browser console . and write some javascript/html5 to test your app.
socket= new WebSocket("ws://"+ window.location.host+"/room1");
socket.onmessage = function(response){console.log(response.data)};
socket.send('hi!!');
and open another browser instance and do same as above and u can see the messages are broadcast on both browsers .
connect and disconnect channels inbuilt function
def ws_connect(message):
    room = message.content['path'].strip("/")
    message.channel_session['room'] = room
    Group('chat-{}'.format(room)).add(message.reply_channel)
def ws_disconnect(message):
    Group("chat-{}".format(message.channel_session['room'])).discard(message.reply_channel)
also route this defintion to routing.py . your routing.py file should look like this.
from channels.routing import route
from chat.consumers import ws_connect,ws_message,ws_disconnect
 
channel_routing = [
			route("websocket.connect", ws_connect),
			route("websocket.receive",ws_message),
			route("websocket.disconnect", ws_disconnect),
		]

Now you have fully working real time django app .


Reference:

https://github.com/andrewgodwin/channels
https://youtu.be/2sEPipctTxw