mandaputtra
mandaputtra

Reputation: 1070

Send specific message to specific socket.id with socket.io

I'm having problem finding the right answer for my problem. I want to had private messaging for every user like Telegram if I may say. Or like notifications on StackOverflow the socket event are only send to specific user.

io.on('connection', function (socket) {
  // this will be only sent to a user that just connected
  socket.emit('news', { hello: 'world' });
});

But how to send specific message with custom id?

Here my socket.js

const socketio = require('socket.io')
const { redis, saveUser } = require('./redis')

module.exports.listen = function(app){
io = socketio.listen(app)

  io.on('connection', socket => {
    console.log('connected user', socket.id)

  socket.on('join', (payload) => {
    redis.get(payload.email (err, socket_id) => {
      socket.broadcast.to(socket_id).emit('join', `Hello ${payload.whoChat.name} Chat you`)
      })
    })      
  })

return io
}

but this doesn't send anything to my user, if using rooms it will send directly to the rooms and when i look for docs io.to() and io.broadcast.to() can be use with sockets rooms.

so i decided to take it simple but wrong here my server.js rigth now.

io.on('connection', function (socket) {
  socket.on('join', payload => {
   socket.emit('join', payload)
})

and on client-side

socket.on('join', (payload) => { 
    // Compare data from socket with local data if match then push the message 
    // to users who recieve
    if ( payload.userId === localData.userId ) {
        this.message.push(payload.message)
    }
})

but with that actually I send it to all users... how to do it properly and right? and how to save the users socket.id? since socket.id are generated randomly how do you save it for the future request when user disconnect?

Upvotes: 1

Views: 9875

Answers (1)

molamk
molamk

Reputation: 4116

You need to maintain a map of _socket_id/user_id_

Server

const sessionsMap = {};

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

  socket.on('userIdReceived', (userId) => {
    sessionsMap[userId] = socket.id;
  });

  socket.on('send', (message) => {
    const receiverId = sessionsMap[message.receiverId];
    const messageData = message.data;
    socket.broadcast.to(receiverId).emit('my message', messageData);
  });
});

Client

const userId = 'FOO';

io.on('askForUserId', () => {
  io.emit(userId);
});

io.on('send', (message) => {
  console.log('You received a message');
  console.log(message.data);
});

Note

Make sure to check out the Socket.IO cheatsheet it covers a lot of commands and use cases.

Upvotes: 4

Related Questions