Hugo
Hugo

Reputation: 102

socket emit to only one user

I´ve been searching for the anwser but most of them i cant quite connect with my code so im hoping to get some help.

I want to send a message for a specific user, like a chat beetween 2 people.

For example, if i choose John how can i only send a mensage to him? im having much trouble in this

enter image description here

app.js

io.on('connection', function (socket) { 
  socket.on('chat', function (data) {
      console.log(data);

      //Specific user
      //socket.broadcast.to(socketid).emit('message', 'Hello');

  });
});

I have a mongodb database so how can i specify the socketid having the user id of the select user?

Upvotes: 2

Views: 3101

Answers (2)

ellipsis
ellipsis

Reputation: 12152

The below code can be used to send message to a specific client. Point to be noted , every client connected has a unique socket id. Store that id in an array. You can call any user with that id.

var id=[];
    io.on('connection', function (socket) { 
      socket.on('chat', function (data) {
          console.log(data);
    id.push(${socket.id});


      });
    });

   //to send to specific user
 io.to(socket#id).emit('hey!')

Upvotes: 1

Adrian Preuss
Adrian Preuss

Reputation: 3113

You must create an userbased array. Here, you can get a special socket:

var users = [];

io.on('connection', function (socket) {
    users.put(socket);

    socket.on('chat', function (data) {
        console.log(data);

        users[0].emit('chat', data);
    });
});

You can use a array based or an object based (here you can store it with the username, but you must implement a procedure to set the username after connection is available) variable.

Upvotes: 0

Related Questions