【问题标题】:How to send data to all subscriber using Socket.io in node app如何在节点应用程序中使用 Socket.io 向所有订阅者发送数据
【发布时间】:2018-04-05 18:20:04
【问题描述】:

这是事后路线。当用户发布事件时,该事件应发送给其所有关注者! 我为此维护了 Follower Array。

如何使用 Socket.io ????

 module.exports.postEvent = (req,res) => {
       Events.saveEvent(req.body , (err,saveEvent)=>{
          var response = {
              status : 500,
              message : err
          };
          var id = req.userId;
          if(err){
              res.status(response.status)
                  .json(response.message);
          }else {
              // find the data of user from token and
                user.getuserbyname(id ,(err,user)=>{
                    if(err){
                        res.status(response.status)
                            .json(response.message);
                    }else{

                        // send to all user subscribers via socket.io
                        async.each(user.followers ,(id , callback)=>{

                         what will be the code here???


                        })
                    }
              })
          }
      })
    };

【问题讨论】:

  • 我建议提供更多代码,例如在后端实现套接字库的位置。你用的是快递吗?
  • 是的,我正在使用快递。在我的 ASYNC.each 循环中,我正在迭代一个关注者数组,我想向每个订阅者或关注者发送一个新帖子,那么我需要在那个 for 循环中写什么?

标签: node.js mongodb sockets express


【解决方案1】:

在设置io 服务器时附加io instance to your app

app.io = io;

然后可以通过请求对象获得

router.post('/event', function(req, res){
  req.app.io.emit('message', data)
})

默认房间

每个套接字连接都有一个由其Socket#id 标识的"Default Room"

你可以在你的请求处理程序中发送到那个房间:

req.app.io.to(socket_id).emit('my message', msg)

或通过套接字 io 处理程序中的套接字:

socket.broadcast.to(socket_id).emit('my message', msg)

房间

SocketIO 还提供了Rooms 的概念。您可以将套接字joinleave 设置为一个房间,然后发射到该房间,而不是自己管理订阅数组。

io.on('connection', function(socket){
  socket.join(`room:${user}`)
})

io.to(`room:${user}`).emit('my message', msg)

【讨论】:

  • 如果我创建一个房间!我怎么知道前端的那个房间?
  • 基于前端和后端共享的一条数据。或在与房间名称连接时发出消息。
猜你喜欢
  • 1970-01-01
  • 2020-06-11
  • 2016-03-27
  • 2019-04-12
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
相关资源
最近更新 更多