简体   繁体   中英

Connections are duplicationg in Socket.io

I'm developing a chat app, and the connections are duplicating.

In my route, I have:

exports.index = function (io) {

  return function (req, res) {

    var userId;

    res.render('index', {
      title: 'RandomChat.me',
      test: 'test2'
    });

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

      userId = socket.id;
      console.log("+++++++++++++++++++" + userId);
      socket.emit('addUser', { userId: userId });
      socket.room = 'General';
      socket.join(socket.room);

      socket.on('sendMessage', function (data) {
        console.log(data.room);
        // socket.broadcast.emit('receiveMessage', { data: data });
        socket.broadcast.to(data.room).emit('receiveMessage', { message: data.message });
      });

    });

  }

};

Client-side something like:

  var socket = io.connect('http://domain.com:3000'); 
  var userId;

  socket.on('addUser', function(data) {
    userId = data.userId;
    console.log(userId);
  });

  socket.on('receiveMessage', function (data) {
    console.log(data);
  });

  var room: "General";
  var message: "Test";
  socket.emit('sendMessage', { room : room, message: message });
  console.log(userId + " " + message)

If I go to the app and check the console log, I see the userId, and when I reload the page, I see the same ID's twice, if I reload again, I see it 3 times and so on.

The same thing is happening in the node.js console.

So basically when connections/users are duplicated, the other users receive duplicate messages, as the sendMessage/receiveMessages functions are run more than once.

Help appreciated.

Using io.sockets.once('connection', function (data){}) instead of io.sockets.on('connection', function (data){}) fixed it. It doesn't try to recover a lost connection.

The problem is this line

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

You should not put these inside a request handler because its just wrong to add a connection handler for socket for each request. Try doing these outside the request handler and use the io object to emit/broadcast events to sockets from the request handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM