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.
pip install -U channelsAfter 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 runserverGo 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 .
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 .