Socket.io respond to sender - javascript

What I'm trying to do is have socket respond to the sender ONLY. What I'm currently doing:
When user visit webpage I included js so he connects on server (on all webpages) but i'm not sure here when user reload page or just switch pages will he be reconnected every time or connection stays the same ?
Now I'm sending data to my node.js app that do something with it but in case of error/success How can I emit to specific client that send data (now i emit data for every user that is connected)

You have to call emit on the socket object :
io.on('connection', (socket) => {
socket.on('event', () => {
socket.emit('otherEvent', { data : ... });
});
});

Related

Vue & Sockets: Handling sending messages back and forth

I have a simple implementation, or an attempt at one, of a messaging system just to show an alert of a message to different users. I'm using https://www.npmjs.com/package/vue-socket.io Vue Socket Io but it's just a socket.io. I am attempting to have the client subscribe to an event in mounted. The name is based on their userID. The problem is that my implementation below doesn't work to show the alerts. I can see the event being subscribed to in mount and I can see sending message console log in the server so I know that is getting fired but I don't see the alert being triggered by the emit(Chat_....
server:
io.on('connection', function(socket) {
socket.on('sendMessage', function (data) {
console.log("Sending message to" + data.user);
socket.emit(`CHAT_${data.user}`, data.msg)
});
});
client:
On the client, the userIDSelf is a user ID that is passed in as a prop. It's the User's logged in ID and in mounted, they automatically subscribe to the a chat channel with their userid appended to it, like a custom channel.
mounted() {
this.sockets.subscribe(`CHAT_${this.userIDSelf}`, (data) => {
alert(data)
});
},
there is a function sendMessage that takes the values from 2 inputs (not seen) in the template. You have to enter a user ID on who you want the message sent to and then another input with the actual message. These are sent over to the backend server listed above.
methods: {
sendMessage() {
this.$socket.emit('sendMessage', {user: this.userIDReceiver, msg: this.message})
},
}
I see a logical problem here. In your server code
io.on('connection', function(socket) {
socket.on('sendMessage', function (data) {
console.log("Sending message to" + data.user);
socket.emit(`CHAT_${data.user}`, data.msg)
});
});
the socket (User 123) which emitted sendMessage event to the server, will eventually also be the socket which will receive the emitted CHAT_456 event from the server. But User 123 socket only listens to CHAT_123 events. The socket is sending itself a message but doesn't receive it.
Possible Solutions
A - the room approach
Once a socket connects on the server, throw it in a room based on it's user id. This requires sending the userid to the server during connection, e.g. with a query parameter. In the client just add a token query parameter to the connection string like
const io = require('socket.io-client');
const socket = io("https://server-domain.com/?token=" + userid);
and through the connecting socket in a room (join) on the server side like
io.on('connection', function(socket) {
const userid = socket.handshake.query.token;
socket.join(userid);
});
then your socket sendMessage would work like this
/* ... server side */
socket.on('sendMessage', function (data) {
console.log("Sending message to" + data.user);
io.to(data.user).emit('chatMessage', data.msg);
});
B - the keep reference to the socket approach
Internally every socket has a socket id. Normally these are not exposed the user/clients. However you do have a unique user id. So let's keep a user id / socket instance - relation on the server side, so you can get a reference to the socket object for each corresponding user, using the user id.
The most basic example for it would be a in-memory store on the server side
let socketRefs = {};
io.on('connection', function(socket) {
const userid = socket.handshake.query.token;
socketRefs[userid] = socket;
});
then your socket sendMessage would work like this
/* ... server side */
socket.on('sendMessage', function (data) {
console.log("Sending message to" + data.user);
let targetSocket = socketRefs[data.user];
targetSocket.emit('chatMessage', data.msg);
});

Socket.io message after database update

Is it possible to send message (for example using alert) to all users when admin changed something in database?
situation: Users browsing car offers and while doing this admin changed price of few offers --> users gets notifications.
Just couple the event of the database update to an emit like this:
Backend
io.on('connection', (socket) => {
console.log('A user connected');
// handling event from the front-end:
socket.on('clientEvent', function(data) {
// Database update happens before this
socket.emit('databaseUpdate', { description: 'Database is updated'});
});
});
This way every time a database update happens a new event will be emitted to the frontend to all the users which are connected. Your frontend now can listen to it as follows (the frontend who is connected listened to emitten databaseUpdates from the backend):
Frontend
var socket = io();
// now we just log the updated data but in this callback you provide your own implementation.
socket.on('databaseUpdate', (data) => console.log(data.description));
Hopefully you find this answer usefull more info here
source1
Source2
You can use socket.blast() at the end of each db operation.
So, if any user is listening to the blasted message, you can make the API call so that it fetches the new record.
[http://node-machine.org/machinepack-sockets/blast][1]

get tab's socket instance on server

I have to get socket instance in my ajax request on server in node.js module. Here is my code.
app.js
io.set('authorization', function (handshake, callback) {
if (handshake.headers.cookie) {
cookieParser(handshake, null, function(err) {
handshake.sessionID = handshake.signedCookies['express.sid'];
});
} else { return callback('No cookie transmitted.', false); }
});
io.sockets.on('connection', function(socket) {
var session = socket.handshake.session;
var userid = session.userid;
socket.join("room");
//make user offline
socket.on('disconnect', function() {
//my code goes here...
//make user offline
})
});
Now in one of my ajax request, I want socket instance
app.post('/logout', function (req, res) {
//here i want socket instance, so I can emit message to all socket, accept this.
});
As I know, each tab creates it's own new socket connection, but session is unique between all tabs of browser. So, How Do I store socket for each tab on server side, where I can find easily socket instance, and then broadcast message to all sockets, excluding that socket which is creating events. (means user's active tab's socket connection)
any guess.
thanks
In my app, I can do what you say because i use namespace and room and so in a room i can find every socket of someone.
io.of('/user').clients(idRoom);
So that i can remove every socket of the user. But if you cannot use this, i think in your app you will have to implement outside socket.io a class for someone (using session as a way to see if it's already have a socket open or if you have to create a new instance). And in this class, have a socket table so that you will be able to handle socket of someone.
In my case, i do the same except that i use the room of socket.io to do that.
And to broadcast to every socket, it depends what is your app. If your app send to anyone in the same namespace, it doesn't change anything because the socket of the same session will also receive the message. But if not, you will have to implement a function to emit to every socket of the table i suggested above.
In my case i use the 'exclude' to ensure the current socket doesn't receive the message but usually you can use broadcast.
io.of('/user').in(this.id).except(socket.id).emit('msg', { text: text,type:person});
To conclude, socket.io will not help you to handle session and several socket for one user/session but you can manage to deal with it using room feature (in my case it was the best way), or implement a user class where you will manage a table of your session sockets.

Stay Connected to Socket.io while switching pages

I have a phonegap app in which i connect to my node.js socket like so:
var socket = io.connect('http://54.213.92.113:8080');
It works fine but when I go to a different page, the socket gets disconnected.
I could just write the same code in the javascript on the next page but that's messier than I think it needs to be - as it would open up a new connection when it could have just stayed connected in the first place.
Is there any way to stay connected to the socket even if I switch pages?
suppose you have a multi-page application then ,here you can do a trick that when your socket gets connected first time when the page loads then you can assign the session id to that particular connection like this.and then bind that connection to that session.
io.on('connection', function(socket) {
socket.on('start-session', function(data) {
console.log("============start-session event================")
console.log(data)
if (data.sessionId == null) {
var session_id = uuidv4(); //generating the sessions_id and then binding that socket to that sessions
socket.room = session_id;
socket.join(socket.room, function(res) {
console.log("joined successfully ")
socket.emit("set-session-acknowledgement", { sessionId: session_id })
} else {
socket.room = data.sessionId; //this time using the same session
socket.join(socket.room, function(res) {
console.log("joined successfully ")
socket.emit("set-session-acknowledgement", { sessionId: data.sessionId })
})
}
});
Now you had binded the socket connection to a session now you are sending an acknowledgement too at the client side also .There what you can do is that store the session id to the web browsers session storage like this
At client side code
socket.on("set-session-acknowledgement", function(data) {
sessionStorage.setItem('sessionId', data.sessionId);
})
This will store the session id in the browsers session storage.Now when the page is navigated from page1 to page2 and so on. then send that session id to the server so that you will be connected to the same session logically like this
var session_id;
// Get saved data from sessionStorage
let data = sessionStorage.getItem('sessionId');
console.log(data)
if (data == null) {
session_id = null//when we connect first time
socket.emit('start-session', { sessionId: session_id })
} else {
session_id = data//when we connect n times
socket.emit('start-session', { sessionId: session_id })
}
So basically the logic behind is that we can use same session for multiple socket connections by doing this as every time the socket will be joined to that particular room only and emit the events which you can listen on server side and vice a versa.
Only if you build it as a single page application where the actual page doesn't reload load when navigating. However it would probably be better to design your socket.io code and your server side to be resilient to frequent socket connect / disconnect. This is especially true for code written to run on a cell phone.

Is it possible to update a single part of a page using Nodejs and Socket.io?

I'm trying to create a basic Node application, every time a client connects I want to update the counter which is displayed on the page. (My goal is to create this application in its most simple, and learnable form to demonstrate node to my lecturer).
Server side application snippets:
Making the connection
var clients = 0;
io.sockets.on('connection', function (socket) {
socket.on('connect', function () { clients += 1 });
socket.on('disconnect', function(){ clients -= 1 });
});
Rendering the page
app.get(navigation.chat.page, function(req, res){
res.render('chat', {
title: navigation.chat.title,
connected: clients
});
});
Chat page jade template snippet:
span#client_count #{connected}
| connected clients
Client side jQuery, Socket.io and JavaScript
var socket = io.connect('http://localhost');
$(document).ready(function(){
socket.on('connect', socket.emit('connect'));
});
Problem:
The number of connected clients only updates upon page refresh. I would like the number to be updated asynchronously. I'm quite new to node, socket.io and express so i'm unsure how to tackle the problem!
rather than incrementing on client side, better keep counter value on server side, increment on connection and decrement on disconnect io events. Then, you can send updated counter (in the same event handlers where value was changed). On client side, listen for event with counter and when received, replace value in html.
server :
var users_count = 0;
io.sockets.on('connection', function (socket) {
//on connection, update users count
++users_count;
//send it to every opened socket
io.sockets.emit('users_count', users_count);
//when this socket is closed
socket.on('disconnect', function () {
//user disconnected
--users_count;
//emit to every opened socket, so everyone has up to date data
io.sockets.emit('users_count', users_count);
});
});
client :
jQuery(function($){
//connect to localhost
var socket = io.connect('http://localhost');
//handle users_count event, by updating our html
socket.on('users_count', function(data){
$('#client_count').text(data);
});
});

Categories

Resources