0

I'm asking myself : "How could I trigger an IO event to a specific user (like notification when sucess on something)". But on a post request for example I don't have any socket objet.

I want to be able to do this: (should I store the socket object in a cookie? Or there are other possibilities availible?)

app.post('/askChangeUserPass', ChangePassIfCorrect , function (req, res){
    if (req.session) {

        if ( req.data == 1 ){
            return res.send("1") // socket.emit("notification", {})
        } else {
            return res.send("req.data") // socket.emit("notification", {})
        }

    } else {
        return res.render("404")
    }

});
Izio
  • 378
  • 4
  • 15

2 Answers2

1

Since it appears you already have a session for each user, then the usual way to do this is to store the socket.id in the session when the user connects with socket.io. Then, from any http request, you can get the socket.id from the session and use:

// get socketid from session
io.to(socketid).emit(...)

For sharing a session between socket.io and express, see:

How to share sessions with Socket.IO 1.x and Express 4.x?

And, when the socket.io connection is created in the connect event, you can set the socket.id into the session.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
  • I see, but how to store the socket.id in my session, I'm using express-session, and I have it on every request (request.session) but I can't imagine how to link the socket.id obtained in the io.on("connection", function(socket) ) to my session.socketId – Izio Mar 06 '18 at 09:38
  • 1
    @Izio - In the link to the share sessions post in my answer, it shows you how to get access to the session from any `socket`. So, in the `connect` event, you can do `socket.request.session.socketid = socket.id;` (and then perhaps save your session data if your session store needs an explicit save). Then, in any of your other request handlers, you can access `req.session.socketid`. – jfriend00 Mar 06 '18 at 16:27
0

Another way to do this would be to have each client join a user-specific channel when they first connect/login, and then at any time later you can emit to that channel to communicate with all of those instances.

Instance joins the user-specific channel (on connect or login, etc):

socket.join(user.id)

Server emits a message to each instance (in your POST request, etc):

socket.server.to(user.id).emit(...)
Ryan Ewen
  • 134
  • 8