I have a web app using Django Rest Framework and React. I am trying to add web sockets to it. I opted for Django channels as they are the most recommended.
However, I keep getting this error Firefox can’t establish a connection to the server at ws://localhost:3000/ws/canvas_data & then the socket is closed automatically. Apparently, the connexion can not be maintained between the frontend & the backend. I tried several options in the Routing URLs but nothing worked. Maybe the problem is in the port since the same is used by HTTP & ws.
This is my first time dealing with Django Channels so please excuse my lack of knowledge.
This is the consumer:
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from time import sleep
import json
class WSConsumer(AsyncWebsocketConsumer):
async def connect(self):
print("CONNECTION IS NOW OPEN !!")
await self.accept()
for i in range(20): #The logic should be here, this is just an example to test
await self.send(json.dumps({"nom_rapport": "pv"}))
sleep(1)
async def disconnect(self, message):
print("CONNECTION IS NOW CLOSED !!")
pass
the asgi.py configuration:
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.urls import path
from Dashboard.consumers import WSConsumer
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Dashboard_sise.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': URLRouter([
path(r'ws/canvas_data/', WSConsumer.as_asgi()),
])
})
settings.py file:
INSTALLED_APPS = [
.....
'channels',
'rest_framework',
.....
]
WSGI_APPLICATION = 'Dashboard_sise.wsgi.application'
ASGI_APPLICATION = 'Dashboard_sise.asgi.application'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": ['redis://localhost:6379']
}
},
}
The WebSocket is declared like this:
componentDidMount(){
var socketPath = 'ws://localhost:3000/ws/canvas_data';
const Socket = new WebSocket(socketPath);
Socket.onopen = () => {
console.log('Socket is connected');
}
Socket.onmessage = (e) => { //Logic will be placed here
console.log("MESSAGE :", e.data);
this.setState({messages: e.data});
};
Socket.onclose = (e) => {
console.error('Chat socket closed unexpectedly');
};
}
The front end is running on port 3000, while the back is on port 8000.
Thank you in advance.
You have to start a server that supports sockets like daphne
daphne -b 0.0.0.0 -p 8001 django_project.asgi:application