Socket.io在页面刷新时创建多个连接

时间:2018-05-05 01:51:15

标签: javascript express socket.io

我正在制作一个聊天室,但每次刷新页面后,都会建立更多连接。例如,如果我转到我的聊天室页面,则只创建一个连接。但是,刷新一次后,现在连接了2个客户端。每次刷新页面后,都会再添加一个连接。

这是我的聊天路线

    /* GET home page. */
router.get('/', accessControl.ensureAuthenticated, function(req, res, next) {
  const io = req.app.io;
  console.log('const io created');
  io.on('connection', function(socket){
    console.log(' %s sockets connected', io.engine.clientsCount);
    console.log('[NodeApp] (socket.io) A client has connected');
    socket.on('chat message', function(message){
      if (message.sessionID == req.session.id) {
        io.emit('chat message', message);
        console.log('message: ' + message.message);
      } else {
        console.log('client sessionID ('+message.sessionID+') does not match server sessionID ('+req.session.id+')');
      }
    });
    socket.on('disconnect', function(){
      console.log('[NodeApp] (socket.io) A client has disconnected');
      socket.disconnect();
    });
  });

  res.render('chat/index', {
    title: "Chat",
    //send session id for client verification
    sessionID: req.session.id,
  });
});

刷新聊天页面3次后的输出:

const io created
1 sockets connected
[NodeApp] (socket.io) A client has connected
const io created
[NodeApp] (socket.io) A client has disconnected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
const io created
[NodeApp] (socket.io) A client has disconnected
[NodeApp] (socket.io) A client has disconnected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
message: test message (should be sent 3 times)
message: test message (should be sent 3 times)
message: test message (should be sent 3 times)

1 个答案:

答案 0 :(得分:1)

你不能这样说:

io.on('connection', function(socket){...}

在路由处理程序中。每次触发该路由时,您都会为该事件创建另一个侦听器,因此它们堆积了大量重复项,因此您可以在所有这些重复的事件处理程序中多次处理每条消息。

你需要把它放在任何路由处理程序之外。在配置socket.io服务器时,需要配置socket.io服务器及其侦听器,而不是在路由处理程序中。