nodejs and mqtt sending message either once or constantly - javascript

I am using NodeJS with the express and mqtt packages.
Whenever the user pushes the button with the value 'test' a MQTT message should be sent.
However, whenever I send the mqtt message it is send either once when I use 'client.end()' or it keeps on sending the message constantly. I canĀ“t send it twice when I push the button again
I use following code:
module.exports =
{
Send
};
function Send(User){
client.on('connect', function() {
client.publish('alarm/reset', 'Hallo' + Test);
client.end();
});
}
In the '\' following code is used
router.post('/', Authencitation, function(req,res){
var test = req.body.test;
if (test == 'test')
{
reset.Send(req.session.user);
console.log('inside reset');
}
res.redirect('/');
});
However, I alway get inside the function inside reset whenever the button is clicked. It seems it is a mistake made in the function Send(User) but I cannot spot the error.

Following solution worked for me:
function Send(Test){
var mqtt = require('mqtt');
var client = mqtt.connect()
client.on('connect', function() {
client.publish('Test', 'Hallo' + username);
client.end();
});
}

Related

How to use socket.write inside a function

var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('end', function() {
console.log('closed');
});
// connection.write('100');
connection.pipe(connection);
});
server.listen(5001, function() {
console.log('server is listening');
});
function addInput(){
var value = document.getElementById("textId").value;
console.log(value);
document.getElementById("textId").value="";
//connection.write(value);
}
I want to send data to the client in the button function addinput, but I can't send it, how can I use socket.write in the function
Is that code that you commented (connection.write(value);) supposed to work?
You won't be able to make it work since connection is only within the scope of the function you wrote into var server.
Other than that, to get your server to do anything you'll have to make a request to it, possibly with net.createConnection() (check doc here: https://nodejs.org/api/net.html). I'm not seeing any code in your example that would do that so far.

NodeJS - where to place functions for eval()

I have a NodeJS-Server which communicated with the fronend via Websocket-Connection.
When the Server gets a on('message'), it should run a function which name is given the message via eval().
it workes fine, unless I completely don't know where to put the funcions to be called.
var http = require('http');
var ws = require('ws');
function render(vars) {
var server = http.createServer(function(req, res) {
.....
});
/* WEBSOCKET */
var wsServer = new ws.Server({server});
wsServer.on('connection', socket => {
socket.on('message', message => {
console.log('WS from template <-- ', message);
var wsIn = JSON.parse(message);
eval(wsIn.action);
});
});
}
when a message is incoming, eval(wsIn.action) should run a function called.. .lets assume runme.. so where would I now need to declare this function ? I try everything but whatever I do, i get
ReferenceError:: runme is not defined
edit:
I found out something interesting:
when i call a function normal like runme(); in my onMessage.. everything is cool.. but with eval(runme); nothing happens.. no error, no output, nothing..

nodejs and undefined variable, possible scope issue

I have started learning Node JS today and have made a chatroom.
When a user connects, it sends their user information to Node and that will store that in a var called user which is created in the anonymous function of io.on('connecting', function ... so I can have multiples of them for multiple users (I think that would work)
When the user disconnects, I remove an object of their user from usersOnline which is indexed by their user.id
I keep getting this error that tells me it is undefined:
Error TypeError: Cannot read property 'id' of undefined
at Socket.<anonymous> (/var/www/html/projects/hbc_chat/index.js:28:27)
The error is where I use delete usersOnline[user.id]
And here is the code:
// server user
var srvUser = {
id: 0,
display_name: 'HabboCreate',
fancy_display_name: 'HabboCreate',
picture: 'http://www.habbocreate.com/userdata/uploads/2f48a19f199bb5f018b3089fd4967902'
};
var usersOnline = {};
io.on('connection', function(socket) {
var user;
socket.on('connected', function(userObj) {
// store user
user = userObj;
// add to users online list
usersOnline[user.id] = user;
// send to clients
updateUsersOnline();
// send joined message
sendMessage(srvUser, user.display_name + ' joined the chat');
console.log(user.display_name + ' connected');
});
socket.on('disconnect', function() {
try {
// remove their user from the online list
delete usersOnline[user.id];
// send to client
updateUsersOnline();
// send left message
sendMessage(srvUser, user.display_name + ' left the chat');
}
catch (err) {
console.log('Error', err);
}
});
....
This does not seem to be a scope issue. Is it possible updateUsersOnline() changes the user info? I just ran this exact code, very similar to yours, without errors:
var usersOnline = {};
io.on('connection', function (socket) {
var user;
socket.on('connected', function (userObject) {
user = userObject;
console.log('user: ' + JSON.stringify(user));
usersOnline[user.id] = user;
console.log(JSON.stringify(usersOnline) + '\n');
});
socket.on('disconnect', function () {
try {
console.log('user: ' + JSON.stringify(user));
delete usersOnline[user.id];
console.log(JSON.stringify(usersOnline) + '\n');
} catch (err) {
console.log('err: ' + err);
}
});
});
I passed a user created like this in the client 'connected' event:
var userObject = {
id: new Date(),
display_name: 'some_name',
};
my_connection.emit('connected', userObject);
After the connected event I closed the connection. This is what the server logged:
user: {"id":"2016-12-17T04:49:05.123Z","display_name":"some_name"}
{"2016-12-17T04:49:05.123Z":{"id":"2016-12-17T04:49:05.123Z","display_name":"some_name"}}
user: {"id":"2016-12-17T04:49:05.123Z","display_name":"some_name"}
{}
No errors, so it seems something is removing the user object or at least its id property in between your connected and disconnect events.
right, well I've figured out what was wrong.
It was where I was on the chatroom page, I would restart the node server, my JavaScript wouldnt emit the user details (It only done so upon load), so when i went to refresh or whatever, disconnect event wouldn't be able to find info in the user variable and error
My fix was to make a request user event client side and then emit that on the server when there's a new connection, as to not rely on the page load sending the details

WebSockets connection.send not function error

I have a Tornado client application which runs fine at its current state: In a simplified version, it has a structure like the folllowing code piece:
function comms(callback, newSession, connection) {
if (newSession == true) {
connection = new WebSocket('ws://localhost:9022/id/01234');
connection.onopen = function () {
alert("connected");
connection.send('hello world');
};
}
connection.onerror = function (error) {
alert('WebSocket Error ' + error);
};
connection.onmessage = function (e) {
alert('>> message from Host: ' + e.data);
callback(e.data, connection);
}
}
I can connect, I can detect connection is on, I can send messages. I can receive messages. I can forward message via callback function and come back. No problem. All these are done via:
connection.onXXX event handler functions.
Now I want to send some unsolicited messages to server like the following:
function comms(callback, newSession, connection, request=false) {
if (newSession == true) {
connection = new WebSocket('ws://localhost:9022/id/01234');
connection.onopen = function () {
alert("connected");
connection.send('hello world');
};
}
connection.onerror = function (error) {
alert('WebSocket Error ' + error);
};
connection.onmessage = function (e) {
alert('>> message from Host: ' + e.data);
callback(e.data, connection);
}
if (request == true) {
connection.send("request_msg");
}
}
Although connection is open, I can not send such a request message. I receive:
"connection.send is not a function" error.
As I understand, somehow send request must be wrapped into a function, like other connection.onXXXX event handlers. But I do not have any such event or handler.
How can I send my message?
It would seem you would need to do this within an event.
UPDATED:
The onmessage event is what is fired on the server side, so any client processing can't be done in that event handler. I would suggest the client side functionality should be handled in a different function (not comms).
According to this reference tutorial (an-introduction-to-websockets), just call the send request from within the function from the client that requests the message.
Ie. as per the tutorials example, found here, the request is called when the form is submitted / send message button is pressed. This is all wrapped in the onload function.
So you need some client side event or loop that can call the socket connection(socket).send() function, simply passing in text should be sufficient.
Does this help at all or does your application in it's 'complex' state achieve this already?

Websocket second message doesn't send?

I have a websocket where I need to send two messages. It looks like the second message isn't being received. I'm not sure if this is a problem with my code or the websocket itself. I've used the Chrome Advanced Rest Tools Client and was able to send both messages successfully, but I'm not sure why it's not working in my code.
var ws = new WebSocket('ws://localhost:15449/');
ws.on('open', function open() {
console.log('i am open');
ws.send(JSON.stringify(data1));
//ws.send(JSON.stringify(data2));
ws.emit('sendData2');
});
ws.on('sendData2', function sendBar() {
console.log('testing!!');
ws.send(JSON.stringify(data2));
});
ws.on('message', function message(msg1, msg1) {
//the data received is a buffer
console.log('received:', msg1, msg1);
ws.close();
done();
});
Is there not a way to distinguish the different data that is being sent in ws.on('message')?
I figured it out. I needed to add an if check to make sure i got the first data and then send the second one.
var ws = new WebSocket('ws://localhost:15449/');
ws.on('open', function open() {
console.log('i am open');
ws.send(JSON.stringify(data1));
});
ws.on('message', function message(msg) {
if(...) {
ws.send(JSON.stringify(data2));
}
console.log('received:', msg);
ws.close();
done();
});

Categories