M
M
matveyvarg2015-10-26 12:50:51
JavaScript
matveyvarg, 2015-10-26 12:50:51

Why does a block of code fire multiple times?

app.get('/watch/:id',function(req,res){
  roomid = req.params.id;
  Rooms.find({"id":roomid},function(err,rooms){
    if(err !== null)console.log(err);
    //res.send(rooms);
    res.render('index',{title:'Hello'});
    console.log(rooms);
  });
  io.on('connection',function(socket){
    console.log('socket '+socket.id.toString()+' was connected');	
    socket.on('join',function(r_id){
      console.log('type of roomid '+typeof(roomid));
      console.log('type of r_id '+typeof(r_id));
      console.log('r_id='+r_id+'\n');
      console.log('roomid='+roomid);
      socket.join(r_id);
      var clients_in_the_room = io.sockets.adapter.rooms[r_id]; 
      for (var clientId in clients_in_the_room ) {
  				console.log('client: %s', clientId); //Seeing is believing 
      }
    });
  //	socket.join(roomid);
    
    socket.on('message',function(msg,room_id){
      console.log('messg in '+room_id+' room\n'+'room_id type is ' + typeof(room_id));
      var rid = room_id.toString();
      io.to(room_id).emit('message_server',msg);
    });
    socket.on('message_server',function(msg){
      console.log('message_server '+msg);
    });
  });
  
  //res.sendfile('room.html')
});

The first time I redirect to '/watch/:id' everything is fine, but the next time I am redirected to '/watch/:id' (provided that the previous connection was not closed) the code that comes after io.on('connection',function(socket){starts to be duplicated, and messages are displayed by 2, 3, etc. times. How can I make the message appear only once?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
3
3luyka, 2015-10-26
@3luyka

Because with each "app.get(...)" you hang an event on io.on('connection')...
On the first request, you hung this being 1 time, then 2nd, and so on.

V
Vitaly Sivkov, 2015-10-26
@Sivkoff

Take out this code

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

outside the /watch/:id handler, it is processed when the socket is connected and there is no point in weighing it on a GET request.

A
Alexander Aksentiev, 2015-10-26
@Sanasol

How To Get Rid Of Multiple Messages After Re...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question