Django-channels:chatSocket.onmessage or chatSocket.send does not work - javascript

I'm trying to implement a django channels chat app. when the submit button of the room view is clicked, the message does not appear in the chat log. which make me think that somethings wrong with chat.onmessage command, it does not seem to fire. can someone help me fix the issue. here is the code for room view:
<!-- chat/templates/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<button id="chat-message-submit" type="submit" value="Send">Send</button>
</body>z
<script>
var roomName = {{ room_name_json }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
console.log("got to onmessage");
var data = JSON.parse(e.data);
var message = data['message'];
document.getElementById('chat-log').value += (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.getElementById('chat-message-submit').click();
}
};
document.getElementById('chat-message-submit').onclick = function(e) {
var messageInputDom = document.getElementById('chat-message-input');
var message = messageInputDom.value;
console.log("got message : " + message);
chatSocket.send(JSON.stringify({
'message': message
}));
console.log("This was done?");
messageInputDom.value = '';
};
</script>
</html>
Here is my consumer view :
from channels.generic.websocket import WebsocketConsumer
import json
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def recieve(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
self.send(text_data = json.dumps({
'message' : message
}))

I'm so stupid I literally made a typo, used function name "received" instead of "recieved". Thanks I'll go cry in the corner now.

Related

HTML page doesn't show that city does not exist

I am trying to make a website that shows the weather forecast. It already shows the weather forecast. If I want to enter a city that doesn't exist I want a message to appear. I already tried something with 404 but it doesn't show up in the console log. I hope someone can help me. Thank you in advance!
function getData() {
let apikey = 'private';
var city = document.querySelector('#city').value;
let requestURL = 'https://api.openweathermap.org/data/2.5/forecast?q='+city+'&appid='+apikey+'&units=metric';
let request = new XMLHttpRequest();
request.open('GET', requestURL, true);
request.responseType = 'json';
request.send();
request.onload = function () {
let data = request.response;
addData(data);
var body = document.querySelector('body');
var div = document.createElement('div');
for (var i = 0; i < data.list.length; i += 8) {
// console.log(data.list[i].dt_txt);
div.appendChild( createEL('p',
'<b>Date en time: ' + data.list[i].dt_txt+'<br></b>'+
'City: ' + city+'<br>'+
'Country: ' + data.city.country + '<br>'+
'Temperature: ' +data.list[i].main.temp+'<br>'+
'Weather: ' +data.list[i].weather[0].main));
}
if (XMLHttpRequest == '404'){
console.log("Doesn't exist")
}
var body = document.querySelector('body');
body.appendChild(div);
function createEL(tag, content){
var el = document.createElement(tag);
el.innerHTML = content;
return el;
}
}
}
var button = document.querySelector('#show');
button.addEventListener("click", function (ev) {
ev.preventDefault();
getData();
},false);
function addData(jsonData) {
var city = document.querySelector('#city').value;
var input = document.querySelector('#city');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather</title>
</head>
<body>
<h1>Weather</h1>
City: <input type="text" id="city" name="city" placeholder="city">
<button id="show" name="show">Show</button>
<script src="js/weather.js"></script>
</body>
</html>
XMLHttpRequest will never be equal to 404. It is the constructor function you used to created the object that made the HTTP request!
You need to examine request.status.
You need to check request.status if you are sending status code from API.
let request = new XMLHttpRequest()
console.log(request.status);
To display does not exist you can check the response data length like
if(data.list.length==0)
{
console.log("Does not exists.");
}

Sending test message from JAVASCRIPT to python

Sorry for the noob questions, i'm new on it.
I have a python server, and client and it's working.
There are :
import socket
def Main():
host = "127.0.0.1"
port = 5000
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
print ("from connected user: " + str(data))
data = str(data).upper()
print ("sending: " + str(data))
conn.send(data.encode())
conn.close()
if __name__ == '__main__':
Main()
and client
import socket
def Main():
host = '127.0.0.1'
port = 5000
mySocket = socket.socket()
mySocket.connect((host,port))
message = input(" -> ")
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print ('Received from server: ' + data)
message = input(" -> ")
mySocket.close()
if __name__ == '__main__':
Main(
But when i want to make the same client but via JAVASCRIPT, i don's see this messages on server. Could someone please explain why?
There is my html file
<head>
<title>Test</title>
<script src="jquery.js"></script>
<script type="application/javascript">
var ws;
function init() {
var servermsg = document.getElementById("servermsg");
ws = new WebSocket("ws://127.0.0.1:5000/");
ws.onopen = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server connected";
};
ws.onmessage = function(e){
servermsg.innerHTML = servermsg.innerHTML + "<br><< Recieved data: " + e.data;
};
ws.onclose = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server disconnected";
};
}
function postmsg(){
var text = document.getElementById("message").value;
ws.send(text);
servermsg.innerHTML = servermsg.innerHTML + "<br>>> Data sent: " + text;
}
</script>
</head>
<body onload="init();">
<form action="" onSubmit="postmsg();return false;">
<input type="text" name="message" value="" id="message">
<input type="submit" name="submit" value="" id="submit">
</form>
<div id="servermsg"><h1>Message log:</h1></div>
</body>
Thank you everyone for the help

IE 11 Crashes In Windows 10

I'm experiencing an issue with a login page. When the page loads the F12 Developer tools gives this error - SCRIPT1002 on FWi.js (1,1). When I put in the login information and submit the tab crashes and reopens. This is the script information from that file.
<script src="../../js/lib/jquery.min.js"></script>
<script type="text/javascript" src="../../js/lib/gibberish-aes-1.0.0.min.js"></script>
<script>
var encrypt = function(uobj, token) {
var str = JSON.stringify(uobj);
var encrypted = GibberishAES.enc(str, token);
return escape(encrypted);
};
$(document).ready(function() {
$("#submitButton").click(function(event) {
event.preventDefault();
var loginForm = document.getElementById("loginform");
var un = $(loginForm).find('#user-name').val(),
up = $(loginForm).find("#user-pass").val(),
tok = $(loginForm).find("#ekey").val();
var encrypted = encrypt({username:un, password: up, instanceType: "browser"}, tok);
$("#user-name").remove();
$("#user-pass").remove();
var encup = $('<input type="hidden" name="authorization" value="Bearer ' + encrypted + '"/>');
$(loginForm).append(encup);
loginForm.submit();
});
});
</script>
Any ideas what could be causing this issue?

Why i can't receive messages in strophe js?

I have this code.I send messages to server but i don't receive them.I have code from a post where the user say is working.I have a xmpp server where i can connect with strophe.
<html>
<head>
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="strophe.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="init">
</div>
<script type="text/javascript">
BOSH_SERVICE = 'http://localhost:5280/http-bind/';
xmpp_user = "user";
xmpp_domain = "localhost";
xmpp_userdomain = "user#localhost";
xmpp_password = "secret";
angular.
module('myApp', []).
controller('init', function(xmppAuth){
xmppAuth.auth(xmpp_userdomain,xmpp_password);
on_presence = function (presence){
console.log('presence');
return true;
}
on_message = function (message){
//console.log('message');
console.log(message);
return true;
}
}).
service('xmppAuth', function() {
return {
auth: function(login, password) {
connect = new Strophe.Connection(BOSH_SERVICE);
connect.connect(login, password, function (status) {
if (status === Strophe.Status.CONNECTED) {
console.log("Autentificare reusita!");
//try send helo
var message = "helo";
var to = "marian#localhost";
if(message && to){
var reply = $msg({
to: to,
type: 'chat'
})
.cnode(Strophe.xmlElement('body', message)).up()
.c('active', {xmlns: "http://jabber.org/protocol/chatstates"});
connect.send(reply);
console.log('I sent ' + to + ': ' + message);
}
//addhandler receive messg
connect.addHandler(onMessage, null, "message", null, null, null);
var onMessage = function (message){
console.log('S-a primit un mesaj');
console.log('message');
return true;
}
}
})
}
}
})
</script>
</body>
</html>
What i should do?Thanks for any help!
I had a similar problem and I noticed that setting the handler before sending any message would allow you to read the messages, even those you send.
Below is a working code which I have tested
...
server_connection.connect(user_id, password, function(status){
if (status == Strophe.Status.CONNECTED){
on_connected();
}
});
function on_connected(){ server_connection.addHandler(on_message, null, 'message');}
var on_message = function(message){ /* work with message here */ }
You won't receive messages which you send, only incoming messages, or use MUC plugin for history.

websocket server not receiving message

First I built a websocket server using node js and ws module. Then using chrome and firefox, I connect to that server and the connection is successfully established. However, the message I send from browsers does not arrive at the server. I have some code on server to console.log out if message is received. Nothing appears, however when I refresh the browser, the messages I previously sent arrive. The messages did not arrive when sent them but only once I refresh the page. I don't know why. This seems to work in from some other computers but not mine.
Here is the server code:
var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express();
app.use(express.static(__dirname + '/views'));
var rmi = require('./RMIClient.js');
console.log(rmi);
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
// from here is the logic codes
var clients = [];
var clientId = 0;
wss.on('connection', function(ws) {
console.log("connection established for client "+ (clients.length+1));
clients.push(ws);
console.log("index is " + clients.indexOf(ws));
clientId += 1;
ws.send("Hello Client: " + clientId);
//
// ws.send("Welcome from AMTT Chatting Server");
ws.on('message',function(data){
console.log('message receieved : '+data);
for(var i = 0;i<clients.length;i++){
clients[i].send(data);
}
});
ws.on('a',function(){
console.log("a event fire from client");
});
ws.on('close', function() {
var index = clients.indexOf(ws);
console.log('stopping client interval '+index);
if (index > -1) {
clients.splice(index, 1);
}
});
});
Here is the client code:
<html>
<script>
//var ws = new WebSocket('ws://localhost:8080/');
var messagearea,inputarea,sendButton;
var connection = new WebSocket(/*'wss://echo.websocket.org');*/'ws://192.168.8.195:8080/');
// When the connection is open, send some data to the server
console.log(connection.readyState);
connection.onopen = function () {
console.log(connection.readyState);
inputarea.disabled = false;
sendButton.disabled = false;
};
// Log errors
connection.onerror = function (error) {
console.log('sorry connection fail:' + JSON.stringify(error));
};
// Log messages from the server
connection.onmessage = function (e) {
messagearea.value = messagearea.value + '\n' + e.data;
console.log('Server: ' + e.data);
};
function sendMessage(){
if(inputarea.value !='')
connection.send(inputarea.value);
inputarea.value = '';
}
</script>
<body>
<textarea rows="15" cols="100" id="messagearea" disabled>
</textarea>
<br/>
<textarea rows="2" cols="90" id="inputarea" required autofocus>
</textarea>
<input type = 'button' value = 'send' id = 'sendbutton' onclick = "sendMessage()"/>
</body>
<script>
messagearea = document.getElementById('messagearea');
messagearea.value = '';
inputarea = document.getElementById('inputarea');
inputarea.value = '';
inputarea.disabled = true;
sendButton = document.getElementById('sendbutton');
sendButton.disabled = true;
</script>
</html>
And again I found that kind of situation when I develop that code in java and deployed in wildfly server. I am lost. I think there is something concerned with my network card. Because that same code work perfectly in my friend's machine.
Does anybody experience this situation ? or any solution?
You can also try the following:
connection.addEventListener("message", function (e) {
processSocketMessage(e);
});
good luck :)

Categories

Resources