'Django WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/8_9/' failed:
I am doing a Django project in which I have added a live chat feature using Django channels. When I finished the messaging part I worked on other parts of the project (like posting, liking posts, and in general parts that have nothing to do with the messaging). However now when I test the messaging page I get the following error in my browser console:
8_9:58 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/8_9/' failed:
The error has no further explanation after the colon (which is why I don't even know where to start solving it, I've had similar errors but they always had something else after the colon). I also tried rolling back to an older version of my app using GitHub (I went back to the last version that I was sure was working) and it still didn't work.
Here is my js code:
const roomName = JSON.parse(document.getElementById('room-name').textContent);
var chatSocket = "";
if(document.location.protocol == "https:"){
chatSocket = new WebSocket(
'wss://'
+ window.location.host
+ '/wss/chat/'
+ roomName
+ '/'
);
}
else{
chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/chat/'
+ roomName
+ '/'
);
}
chatSocket.addEventListener('open', function(event) {
$.ajax({
url: '/ajax/get_msg/',
data: {
'room': roomName
},
dataType: 'json',
success: function (data) {
var realData=data[0];
var i=0;
while(i<realData.length){
document.querySelector('#chat-log').value += (realData[i][0] + ': ' + realData[i][1] + '\n');
i++;
}
}
});
})
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
document.querySelector('#chat-log').value += (data.user + ': ' + data.message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message,
}));
messageInputDom.value = '';
};
My routing:
# Django imports
from django.urls import re_path
from . import consumers
# routing to the consumer
websocket_urlpatterns=[
re_path(r'wss/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer),
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer),
]
My consumer:
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from django.contrib.auth import get_user_model
from .models import Message
User = get_user_model()
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# get both users
user = self.scope["user"]
get_ids = self.scope["url_route"]["kwargs"]["room_name"]
ids = get_ids.split('_')
my_user = User.objects.get(username=user.username)
my_id = my_user.id
other_id = 0
if str(ids[0]) == str(my_id):
other_id = ids[1]
else:
other_id = ids[0]
other_user = User.objects.get(pk=other_id)
# save the sent message to a database
new_message = Message(sender=my_user, rec=other_user, text=message, room=get_ids)
new_message.save()
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'user': user.username,
}
)
# Receive message from room group
def chat_message(self, event):
message = event['message']
# get the user that sent the message
user = event['user']
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message,
'user': user
}))
And my settings:
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": REDIS_URI,
}
}
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [REDIS_URI],
},
},
}
Any help would be greatly appreciated
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|