How can i send data to u particular user using socket.io

513 views Asked by At

i am building a mobile app with ionic, i am using socket.io, i want to be able to send message to a particular user with an id, and not broadcast the message to everyone, the chat application is not a chat room style kind of app but a one on one chatting app like watsapp, i searched online but what i saw was not working, here is the code for the server side

const io = require('socket.io')(server);

io.on('connection', socket => {
        console.log('New user connected');
        socket.on('get_all_msg', data => {
            DBConn.query(`SELECT * FROM chats WHERE rec_id = ? || send_id=?`, [data.id, data.id], (error, results, fields) => {
                if (error) throw error;
                io.to(data.id).emit('all_msg', results)
            });
        })
    })

the id of the user i am chatting with is the data.id, i tried using io.to(data.id).emit('all_msg', results) but the user did not receive any message, pls what am i doing that is not right

Here's the client side code

this.socket.emit('get_all_msg', {id:this.contactInfo.id})
this.service.socket.fromEvent('all_msg').subscribe((data:any) => {
    console.log(data)
})

I am using ngx-socket.io in my ionic add

1

There are 1 answers

2
varaprasadh On

we need to map socket id to user id; we can solve this using redis but simple way i did was

actually socket io itself joins the current into a room with its id(socketio) itself; i was like, "why not join that socket into room with user_id"

backend side:

io.on('connection',socket=>{
  socket.on('join-me',userid=>{
     socket.join(userid);
   })
})

front end side:

const socket=io(`blahblah`);
socket.on('connect',()=>{
   socket.emit('join-me',current_user_id);
})

when one user emits new-message event we can get the participent id's and can simply loop over their ids and emit an event

socket.on('message',data=>{
  //do some logic let say 
  participents=data.participents;
  parsedMessage=someLogic(data);
  for(id of participents){
    
     //here is the magic happens io.to(room_id) here room id is user id itself.
     io.to(id).emit('new-message',parsedMessage);
   }
})

works with one to one and group chat!