0
votes

I have new to socket.io and have a plain chat application.

Its a multi user application where chat messages are emitted to all connected users.

Below is my code for server side. Where chat message is the event fired and subscribed to for broadcast of messages

Now my question is, is the code correct ? Specially the disconnect part. Do i have to remove the subscribers or listeners which have been subsrcibed with chat message event on disconnect ?. is this a leak if i don't remove the listeners?

    var server = app.listen(3006);
console.log('listening on port 3006');

//socket io event listening
var io = require('socket.io').listen(server);

io.on('connection', function(socket) {
    console.log('a user connected');
    socket.on('disconnect', function() {
        console.log('user disconnected');
    });
    socket.on('chat message', function(msg) {
        console.log(msg);
        io.emit('chat message', msg);
    });
});
1

1 Answers

2
votes

Do i have to remove the subscribers or listeners which have been subsrcibed with chat message event on disconnect ?.

No. You don't need to do any processing on disconnect unless you have your own data structures that need to be updated.

Users will be automatically removed from all socket.io data structures when they disconnect. You don't have to do that yourself.

Is this a leak if i don't remove the listeners?

No, Javascript is garbage collected so when the socket disconnects and socket.io removes it from all of its data structure, the socket object will be garbage collected as long as you don't have any of your own data structures that keep a reference to the socket object.