Send object to client via Socket.io (Node.js) - node.js

I have the following code written on the node.js side:
var filtered = quadtree.filter(function (element) {
return element.x > min
})
console.log(typeof filtered);//object
socket.emit("Sonuç", filtered);
Here's the html code:
socket.on("Sonuç", function (data) {
console.log(data)
});
There is no connection problem between server and client. I have a variable named filtered on the server side, and I learned that this variable is the object of its type. I do not have anything to send it to the client side and print it on the screen. What function should I use in the code section?

I do not know when you send from server to client in time?
If you send it in connection then you need to open the client first, then start the server then the server sends the data and the client can receive the data.
// server
io.sockets.on('connection', function(socket) {
var filtered = {key: 'value'};
socket.emit("Sonuç", filtered);

Related

Accessing the Data Object of Socket.IO-Server from the Socket.IO-Client

In socket.io server a property can be added to the socket.data object. How do I access such a property at the client side (socket.io-client)?.
// Server code
io.on('connection', socket => {
socket.data.customId = getCustomId();
io.emit('connected', {success: 'true'})
})
// Client code
socket = io('http://localhost:5000');
socket.on('connected', data => {
console.log('SOCKET_DATA:', socket)
console.log('SOCKET_CUSTOM-ID:', socket.data.customId); // produces 'undefined'
})
I would like to access the customId I added at the server from the client side. The data attribute don't even exist on the socket object displayed at the console at the client side.
If you wanted some way to have access to that, you would have to create some request that sends to the server. Only the server stores that information. You could do something like the following on client side:
socket.emit("getCustomId", (id) => {
console.log("SOCKET_CUSTOM-ID:", id);
});
Then the server can listen and respond with the custom id:
socket.on("getCustomId", (callback) => {
callback(socket.data.customId);
});
That callback parameter on the server side connects back to the unnamed ES-6 function declared in the socket.emit("getCustomId"); call, which you can see here on this SO question about socket.io callbacks

Websockets using angular and Nodejs: How to send data to specific client

I am trying to use websocket.io with nodejs and angular. I am trying to build a one-to-one chat application. Here is snippets of my code:
server.js
app.io.on('connection', function(socket){
console.info(`Client connected [id=${socket.id}]`);
socket.on('disconnect', function(){
console.info(`Client gone [id=${socket.id}]`);
});
});
sendmessage.js
router.post("/auth/sendMessage", function(req, res) {
//rest api to handle send message
//mongodb insert
app.io.emit('new-message', { message: message});
}
Angular Client
this.socket.on("new-message", function(data) {
if (
data.message.conversationId === self.conversationId &&
data.message.sender === "customer"
) {
self.messages.push(data.message);
setTimeout(function() {
self.messagesDiv.nativeElement.scrollTop =
self.messagesDiv.nativeElement.scrollHeight;
}, 100);
}
});
Now, the problem that I am facing is new-message will send message to all the listeners. Although, I am handling the logic on the client side, to only show the message if it is sent by specific conversationId, this should be handled at the server end only due to security issues.
So, I want to be able to send to specific users only. I think this can somehow be done using socket.id which would be unique for each connection. But how can I pass this socket.id from client to server, so that server knows on which client it needs to send the data?
There are two things here, app.io and socket. In the first snippet, you use app.io.on('connection', function(socket){. This socket is the new connection. You can store this socket object somewhere in the database or in memory.
Now, app.io.emit will send the message to all the clients, while this socket that you stored somewhere will send the message to that particular client/user on socket.emit.
In short, you need to do
router.post("/auth/sendMessage", function(req, res) {
//rest api to handle send message
//mongodb insert
socket.emit('new-message', { message: message});
}
Here is a small tic-tac-toe game I made using sockets. It will give you more insight on how to use sockets. This is not perfect but you will still understand how to use sockets.
tl;dr save socket from app.io.on('connection'... and use socket.emit to send messages to that particular client.

I am not able to connect to mqtt server from node.js

I am completely new to mqtt and node.js i want to get data from mqtt server at regular intervals and populate in my html5 page
Here is the sample code that am try to connect but not sure it is right way or not
var mqtt = require('mqtt');
// connect to the message server
var client = mqtt.connect('mqtt://test.mosquitto.org');
// publish 'Hello mqtt' to 'test'
client.publish('test', 'Hello mqtt');
// terminate the client
client.end()
Assuming you really are working purely with node.js you haven't given the client time to actually connect before trying to publish a message.
The node.js mqtt module README has a full example (which it appears you've copied and removed most of the important bits from). I have removed the subscription part from the demo code, but this is the bare minimum needed to publish a message.
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');
client.on('connect', function () {
client.publish('test', 'Hello mqtt');
client.end();
});
Following code upload data on hivemq MQTT Broker at regular interval.
var mqtt = require('mqtt');
// connect to the message server
var client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', function () {
setInterval(function () { client.publish('mytopic', 'Hello mqtt') }, 1000)
})
If you want to retrieve that data then use the following function
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})

Sending a login event from server to client

I am trying to set up a chat interface on a site using nodejs.
I need to update the logged_in_user list after a user is authenticated.
I am using this code as a reference
https://github.com/amirrajan/nodejs-chat
io.sockets.on('connection', (socket) => {
socket.on('sendchat', (data) => {
io.sockets.emit('updatechat', socket.username, data);
});
As you can see on the 'connection' event the updatechat event is triggered.
In the client side (public/app.js),the chatlist is updated on getting the updatechat event.
I need to do the same but after a client is authenticated.
Can I somehow tweak the socket object to trigger the event on a 'login' event
This is my code
app.get('/authenticate',function(request,response)
{
var db = couch.db.use('users');
var email = request.query['email'];
var pass = request.query['password'];
db.get(email,{email:email},function(err,body){
if(err)
console.log(err);
else
{
var user_pass = body['password'];
var name = body['name'];
console.log(user_pass);
if(pass == user_pass)
{
eventEmitter.emit('login',name);
response.render('pages/dashboard',{user:body['name']});
}
}
});
// And on 'login' event
eventEmitter.on('login', function(name)
{
// ?????? Broadcast the new user to all logged in users to update the chatlist
});
I have tried to redirect the logged in users to another port and use the socket 'connection' event there.It sort of works but I want to know if there is another approach I could use.
You should use socket.io middleware for authentication.
io.use(function(socket,next){
//auth here
});
Take a look at the docs http://socket.io/docs/server-api/
You can get the req and res objects from the socket object being passed to the middleware.
Note, it is not a great idea to pass a password on the query since the url is not pass ssl.

Send a message from client to server on connection node.js

I want my client-side code to send the server the user's userid when establishing the connection, then i want the server to check the database for new messages for each user that is connecting, and send the user the number of new messages it has when new messages are available.
My client-side code:
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
socket.emit('userid', '1');
});
socket.on('new_message', function (data) {
var number_of_messages= "<p>"+data.number+"</p>";
$('#container').html(number_of_messages);
});
My server-side code:
io.sockets.on( 'userid', function (data) {
console.log('userid: '+data);
});
My problem is that the above code is not working: the userid is never received by the serverside and the on('userid') is never called.
My question is how to know which socket sent this user id and how to send to only this specific socket a certain message.
I have solved the problem by saving the clients socket and their id into a global array. this is not a good solution but it works; I know there are rooms and namespaces but I never used it..
socket.io namespaces and rooms
however,
(I used express)
client:
var socket = io.connect('http://localhost:3000',{reconnection:false});
socket.once('connect', function() {
socket.emit('join', '#{id}');
};
server:
var clients = [];
app.io.on('connection', function(socket) {
socket.on('join', function(data) {
clients.push({
ws: socket,
id: data
});
//retrive the messages from db and loop the clients array
//and socket.send(things)
}
}

Resources