我如何使用socket.io将数据发送给特定用户

问题描述

我正在使用ionic构建移动应用程序,正在使用socket.io,我希望能够向具有ID的特定用户发送消息,而不是向所有人广播消息,因此聊天应用程序不是聊天房间风格的应用程序,但像watsapp这样的一对一聊天应用程序,我在网上搜索,但看到的却不起作用,这是服务器端的代码

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)
            });
        })
    })

我正在聊天的用户的ID是data.id,我尝试使用io.to(data.id).emit('all_msg',results),但该用户未收到任何消息,请问我在做什么,这是不正确的

这是客户端代码

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

我在离子添加中使用ngx-socket.io

解决方法

我们需要将套接字ID映射到用户ID; 我们可以使用redis解决这个问题,但是我做的简单方法是

实际上,套接字io本身使用id(socketio)本身将电流连接到一个房间中; 我当时想,“为什么不使用user_id将那个套接字加入房间”

后端:

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

前端侧:

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

当一个用户发出新消息事件时 我们可以获得参与的ID,并且可以简单地遍历其ID并发出事件

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);
   }
})

与一对一聊天并进行群聊!