0

hello i'm trying to use socket io to get user notification from db. here is how i'm trying to get data and send them back to user

    if(req.user) {
    req.io.sockets.on('connection', function(socket){
    setInterval(getNotf,1000)
    function getNotf() {
    User.findOne({email:req.user.email})
    .then(user=>{
        messages=(user.notifications);
        console.log(messages)
                   socket.emit('output', messages);
});
    }  

});

} the problem with that way is that the message sent to all connected users.how can i send them only to the current user?

thomas g
  • 35
  • 5

1 Answers1

0

You can emit the message to the socket having this connection using its Id:

io.to(socket.id).emit('output', messages)

Within your connection event listener:

req.io.sockets.on('connection', function(socket){
    setInterval(getNotf,1000)
    function getNotf() {
    User.findOne({email:req.user.email})
    .then(user=>{
        messages=(user.notifications);
        console.log(messages)
                   io.to(socket.id).emit('output', messages)
});

I am have a global instance for the connection like this:

var serverhttp = http.createServer(<optionshttp>, app).listen(<port>);
var io = require('socket.io').listen(serverhttp);

As a test with 2 connections you can try this:

        var clients = [];

            req.io.sockets.on('connection', function(socket){ 
                clients.push(socket.id);
                setInterval(getNotf,1000)
                function getNotf() {
                User.findOne({email:req.user.email})
                .then(user=>{
                    messages=(user.notifications);
                    console.log(messages)
                    console.log("socket ID :",socket.id)
                    io.to(clients[0]).emit('output', "user1")
                    io.to(clients[1]).emit('output', "user2")
    //or
    //io.sockets.connected[clients[0]].emit('output', "user1") 
    //io.sockets.connected[clients[1]].emit('output', "user2") 

            });
Farouk Elkholy
  • 913
  • 7
  • 10
  • i tried that also, but if user is connected the message sent also to the other connections – thomas g Nov 16 '17 at 11:52
  • Can you try to log socket.id for your connections, console.log("socket ID :",socket.id). and tell me please how you test this use case of multiple connections ? – Farouk Elkholy Nov 16 '17 at 12:03
  • here is the code on client var socket = io.connect(); socket.on("output", data => { $("#temp").text(data.length) console.log(data) } is right? – thomas g Nov 16 '17 at 12:13
  • I will ask you to do this as a test. in the client: var socket = io.connect("http://localhost:") it is with http:// from the server: io.sockets.connected[socket.id].emit('output', messages) and please tell me your socekt.io version from your package.json file and log the socket.id after on connection event from the server as i asked you – Farouk Elkholy Nov 16 '17 at 12:15
  • can you try the test part in what i edited in my answer and tell me what you got – Farouk Elkholy Nov 16 '17 at 12:26
  • I'm using version 2.04 i'm getting this error an insecure XMLHttpRequest endpoint 'http://localhost:8080/socket.io/?EIO=3&transport=polling&t=L_4qk9D'. This request has been blocked; the content must be served over HTTPS. – thomas g Nov 16 '17 at 12:35
  • if i remove the parameters in io.connect on client side the console output is socket ID : 0shyb48hfV68p980AAAB socket ID : Lv_PtP7LcJNqUQcKAAAC – thomas g Nov 16 '17 at 12:39
  • for the security error you can do this: var socket = io.connect("localhost:",{rejectUnauthorized: false}) but anyway i think you can remove it as you have done (Y) – Farouk Elkholy Nov 16 '17 at 12:43
  • There are actually to 2 different socket with 2 different Ids so you should be able to differentiate for whom you would like to send the message. Did you try the test part ? – Farouk Elkholy Nov 16 '17 at 12:44
  • yes i tried the test, didn't help.but when i user disconnect i get error Cannot read property 'emit' of undefined – thomas g Nov 16 '17 at 12:50
  • should i store the socket id to the user db and then emit the message to only this one? – thomas g Nov 16 '17 at 12:57
  • For this error close the connection for this socket: .io.sockets.on('disconnect', function () { console.log('DIsconnected!!! '); io.sockets.disconnect(); io.sockets.close(); }); – Farouk Elkholy Nov 16 '17 at 12:59
  • This a good link to handle disconnect event: https://stackoverflow.com/questions/17287330/socket-io-handling-disconnect-event – Farouk Elkholy Nov 16 '17 at 13:03
  • For storing the socket ID in a persistent way(DB) no, because this user wouldn't always have this socket connection for ever and his socket id will change but in an array yes(RAM) and you can use a map instead of an array , in order to have for example the key is the userID and his socketID and you will need to manage when this map also on disconnect – Farouk Elkholy Nov 16 '17 at 13:05
  • I forget this in the past comment"for example the key is the userID and his socketID *as the value*" – Farouk Elkholy Nov 16 '17 at 13:12