我正在做一个django项目,其中我添加了一个使用django频道的实时聊天功能。当我完成了消息传递部分时,我处理了项目的其他部分(比如发帖、喜欢帖子,以及与消息传递无关的一般部分)。但是,现在当我测试消息页面时,我在浏览器控制台中遇到以下错误:
8_9:58 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/8_9/' failed:
冒号后面没有进一步的解释(这就是为什么我甚至不知道从哪里开始解决它,我有过类似的错误,但冒号后面总是有其他错误)。我还尝试使用github回滚到我的应用程序的旧版本(我返回到我确信可以工作的上一个版本),但它仍然不工作。
以下是我的js代码:
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 = '';
};
我的路线:
# 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),
]
我的消费者:
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
}))
和我的设置:
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": REDIS_URI,
}
}
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [REDIS_URI],
},
},
}
任何帮助都将不胜感激
暂无答案!
目前还没有任何答案,快来回答吧!