Answer the question
In order to leave comments, you need to log in
Why doesn't WebSocket.onmessage work?
I am using django-channels to establish a socket connection. I did everything as indicated in gettings started.
Messages from the client to the server arrive normally, but they are sent back, they do not reach (socket.onmessage does not work). What am I doing wrong?
def ws_message(message):
action = json.loads(message.content['text'])['action']
if action == "newchat":
response = new_room(message)
message.reply_channel.send(response)
"asd"
elif action == 'message':
response = new_message(message)
Group("room-%s" % json.loads(message.content['text'])['room']).send(response)
"asd"
elif action == 'history':
response = history(message)
message.reply_channel.send(response)
"asd"
socket = new WebSocket("ws://localhost:8000/chat");
socket.onopen = function(e) {
socket.onmessage = function (e) {
alert(e.data);
var jsn = JSON.parse(e.data);
if (jsn['action'] == 'message') {
messageReceived(jsn['message'], jsn['room'], true);
} else if (jsn['action'] == 'history') {
for (var j = jsn['messages'].length - 1; j >= 0; --j) {
messageReceived(jsn['messages'][j], jsn['room'], false);
}
var hist = $('#' + jsn['messages'][0]['chat'] + ' > .chat-history');
hist.animate({scrollTop: hist.prop("scrollHeight")}, 1000);
} else if (jsn['action'] == 'newchat') {
if (jsn['status'] == 'ok') {
var new_elem = '<div id="chat' + jsn['room'] + '" class="sidebar-name"><a href="javascript:register_popup(\'' + jsn['room'] + '\', \'' + jsn['name'] + '\');"><img width="30" height="30" src=""><span>' + jsn['name'] + '</span></a></div>';
$('.chat-sidebar').append(new_elem);
$('#chat' + jsn['room'] + ' a').click();
} else {
$('#chat' + jsn['room'] + ' a').click();
}
}
};
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question