0

I'm trying to implement a small chat application where a user can able to send message to specific Id or set of Id's. I went through the socketio documentation and could find a proper solution. i tried this function

socket.broadcast.to(socketid).emit('message', 'for your eyes only');

but it didnt work.

    let onlineUsers = [];
    let sockets = {};

    module.exports = function (io,app) {

      io.on('connection', (socket) => {

            // Event for user connecting to socket
            socket.on('online', (data) => {
              if(data.username!=null){
                socket.name = data.username;
                onlineUsers.push(data.username);
                sockets[data.username] = socket.id;
                console.log(data.username+' online');
              }
            });

            socket.on('Chat', (data) => {
                socket.broadcast.to(sockets[data.receiver]).emit('message',data.message);
                socket.leave(name);
                console.log('message sent');
            });

    // Event for user going ofline
    socket.on('offline', () => {
        for (var i = 0, len = onlineUsers.length; i < len; i++) {
            if (onlineUsers[i] && onlineUsers[i].username === socket.name) {
                onlineUsers.splice(i, 1);
                delete sockets[socket.name];
                socket.broadcast.emit('offline', {
                    username: socket.name
                });
            }
        }
        console.log('offline');
    });    
}
TRomesh
  • 3,786
  • 5
  • 38
  • 61
  • but it works when you have a correct socketid. i use the same :) – Lycidias May 30 '17 at 19:00
  • when it doesn't work you need to tell me/us the version you use and maybe "a bit" more of code ;) – Lycidias May 30 '17 at 19:05
  • @Lycidias i have updated my code. i need to know whats wron it doesnt throw any errors but nothing happens. – TRomesh May 30 '17 at 19:33
  • Possible duplicate of [Send message to specific client with socket.io and node.js](https://stackoverflow.com/questions/4647348/send-message-to-specific-client-with-socket-io-and-node-js) – mernstacking May 30 '17 at 19:51
  • socket.broadcast.to(sockets[data.receiver]).emit('message',data.message); is the line that doesn't work where you want to send a message only to a specific socket? – Lycidias May 30 '17 at 21:54
  • @Lycidias yes thats the line which doesn't work – TRomesh May 31 '17 at 03:33
  • You want to send a message to sockets[data.receiver] but store currently active socket ids in sockets[data.username] – Lycidias May 31 '17 at 08:21
  • Im storing the current socket.id in sockets array, i have developed it in a way that when ever i refresh the ui it will replace the existing id with new id but since im getting it by the username(reciver name) it will always be the currently available socket. I have done something similar for an earlier version and it worked in there i used **io.sockets.connected[].emit('hey', 'I just met you');** – TRomesh May 31 '17 at 10:54
  • and this is crazy, but here is my number.. so call me maybeee :) ye but log what stand in sockets[data.receiver] at the time you want to broadcast to it and you see it's no valid current socket id – Lycidias May 31 '17 at 15:24
  • @Lycidias i log the **sockets[data.receiver]** value and it seems okay. anyway any suggestion to store it without changing it?. how did you manage to get it working? – TRomesh May 31 '17 at 15:41

2 Answers2

0

I do it like that (copiedand changed a bit from production, i hope nothing important is missing and it works like that)

user = [];

io.on('connection', function(socket){

    user[socket.id] = socket;

    //to send to a group of users which fit with criteria whatever
    socket.on('chatroom1',function(){
        socket.join('chatroomONE');
        io.to('chatroomONE').emit('connections', count_connections);
    });


    socket.on('disconnect', function(data){
        delete user[socket.id];
    });

    socket.on('messagetosb', function(msg){
        var clientid = ""; //here your code to get the client from the users array to whom you want to send a message
        socket.broadcast.to(clientid).emit('antwort', "message x y z");
    });

});
Lycidias
  • 151
  • 8
-1

Consider something like the following:

class Connection {
        constructor(id, socket) {
                this.id = id;
                this.socket = socket;
        }
}

let connections = [];

socket.on('connection', (socket) => {
        // Get an id for the user/connection
        // ...
        // let id = getID(socket);

        connections.push(new Connection(id, socket));
});

let sendToID = (id, message) => {
        for(let i = 0, len = connections.length; i < len; i++) {
                if(connections[i].id === id) {
                        connections[i].socket.emit('message', message);
                        break;
                }
        }
};

Of course, you could use something other than id... but you get the idea.