SocketIO:如何在单个请求中发出事件

时间:2018-12-12 03:33:35

标签: node.js socket.io

我在单个请求中出现发散事件的问题。我已经阅读了Stackoverflow中的许多问题,但是我可以使案件成功。请帮我检查一下。

我的server.js

const express = require('express');
const app = express();

const io = require('socket.io').listen(server)
const socketEvents = require('./socketEvents')
server.listen(PORT, err => {
  if (err) {
    console.log('Cannot run SOCKET!')
  } else {
    app.io = io
    socketEvents(io)
  }
})

然后,这是我的socketEvents.js

const socketEvents = (io) => {
  io.on('connection', (socket) => {
    const socketId = socket.id
    console.log(`User with ID ${socketId} connected`)
    socket.on('disconnect', () => {
      console.log(`SocketId: ${socket.id} disconnected`)
    })
    socket.on('openRoom', function(payload) {
      var roomID = payload.room_id
      var user = payload.user
      console.log('User', 'with socket', socket.id, 'watching', 'room', roomID);
      socket.join(roomID);
    });
    socket.on('leaveRoom', function(uid) {
      console.log('User', socket.id, 'leave', uid, 'room');
      socket.leave(uid);
    });
    socket.on('send-message', (payload) => {
      console.log('User', socket.id, 'send a message data to room', payload.room_id);
      MessageCtr.add_message(payload)
      .then(response => {
        io.to(payload.room).emit("updateRoom_" + payload.room, response)
      })
    })
  })
}

module.exports = socketEvents

我想发出事件:io.to(payload.room).emit("updateRoom_" + payload.room, response),方法为POST时发送请求:

router.post('/new', function(req, res) {
  MessageCtr.add_message({...req.body, 'user_id': req.user.user_id})
  .then(response => {
    req.app.io.to(req.body.room_id).emit("updateRoom_" + req.body.room_id, response)
    res.json({ 'success': true, 'data': response.dataValues });
  })
});

module.exports = router;

此行req.app.io.to(req.body.room_id).emit("updateRoom_" + req.body.room_id, response)不起作用。请给我理由。预先感谢!

我的客户(VueJS):

this.$socket.on('updateRoom_' + this.room.id, function (payload) {
  console.log(payload);
  vm.$store.commit('chat/SEND_CHAT', payload)
})

2 个答案:

答案 0 :(得分:1)

您可以尝试使用全局变量吗 app.io = io替换为global.io = io

global.io.to(req.body.room_id).emit("updateRoom_" + req.body.room_id, response);

代替

app.io.to(req.body.room_id).emit("updateRoom_" + req.body.room_id, response)

答案 1 :(得分:1)

利用Nodejs event emitters解决此问题。

您可以在Api中添加事件发射器(process.emit)。

router.post('/new', function (req, res) {
    MessageCtr.add_message({ ...req.body, 'user_id': req.user.user_id })
        .then(response => {
            // req.app.io.to(req.body.room_id).emit("updateRoom_" + req.body.room_id, response)
            process.emit("send_socket_response", ({ room_id: req.body.room_id, response }));
            res.json({ 'success': true, 'data': response.dataValues });
        })
});

并在您的套接字代码文件中添加侦听器(process.on

const socketEvents = (io) => {
    process.on("send_socket_response", (data) => {
        let room_id = data.room_id;
        let response = data.response;
        io.to(room_id).emit("updateRoom_" + room_id, response)
    })
    io.on('connection', (socket) => {
        const socketId = socket.id
        console.log(`User with ID ${socketId} connected`)
        socket.on('disconnect', () => {
            console.log(`SocketId: ${socket.id} disconnected`)
        })
        socket.on('openRoom', function (payload) {
            var roomID = payload.room_id
            var user = payload.user
            console.log('User', 'with socket', socket.id, 'watching', 'room', roomID);
            socket.join(roomID);
        });
        socket.on('leaveRoom', function (uid) {
            console.log('User', socket.id, 'leave', uid, 'room');
            socket.leave(uid);
        });
        socket.on('send-message', (payload) => {
            console.log('User', socket.id, 'send a message data to room', payload.room_id);
            MessageCtr.add_message(payload)
                .then(response => {
                    io.to(payload.room).emit("updateRoom_" + payload.room, response)
                })
        })
    })
}