Igor Martins
Igor Martins

Reputation: 2047

Socket.io duplicate emit on second window

I'm testing socket.io and do a simple chat message (following the tutorial in the official website)

I opened 2 windows:

When I emit the event in the first window opened, its ok.

But, when I emit the event in second window this send the event 2 times(duplicated).

PS: if I open a third window, this send the event 3 times

Node.js code:

router.get('/', function(req, res, next) {

 res.render('index', { title: 'Express' });

 io.on('connection', function(socket) {
  socket.on('chatMessage', function(msg){
  io.emit('chatMessage', msg);
  });
 });
});

Client side:

methods: {
  sendMessage: function () {
  socket.emit('chatMessage', this.text);
}


socket.on('chatMessage', function(msg){
 console.log('Client side message: ' + msg)
 vmIndex.messages.push(msg);
});

Upvotes: 0

Views: 1415

Answers (2)

M Mickler
M Mickler

Reputation: 11

As Eric mentioned, move your connection listener outside of the / route in order to prevent it from getting created every time someone visits the page.

router.get('/', function(req, res, next) {
 res.render('index', { title: 'Express' });
});

io.on('connection', function(socket) {
  socket.on('chatMessage', function(msg){
    io.emit('chatMessage', msg);
  });
});

Upvotes: 1

Eric Guan
Eric Guan

Reputation: 15982

It's because you're creating a connection listener every time someone visits the '/' route. Try moving the socket-io code outside of the '/' route function.

Upvotes: 1

Related Questions