Ad

Node.js How To Find And Stop Socket Connection

- 1 answer

I am using socket.io in one of express route to populate data from server and send it to on client with different event names, firstsocket and secondsocket.

var io
router.get('/start', function(req, res, next) {
    io = req.app.get('socketio');
    var socketlist = [{name:"firstsocket"},{name:"secondsocket"}]
    for (var key in socketlist){ 
        myInterval = setInterval(function(){
         JsonObj.marks = socketlist[key].name+' '+parseInt(Math.random()*100);
         io.emit(socketname, JsonObj);  
        }, 2000); 
    }   
});

it is working and i can see the data on client console for these to socket events. Now i want to stop one of the socket event based on user button click. I am not getting idea to list and stop sockets.

router.get('/stop', function(req, res) {
    if(req.socketname=='firstsocket') {
     //stop and destroy firstsocket
    }
    if(req.socketname=='secondsocket') {
     //stop and destroy secondsocket
    }
    res.redirect('/');
 });

please suggest, how to identify and stop one socket session out of multiple sessions.

Thanks

Ad

Answer

If you store the socket.id information of each socket within your

var socketlist = [{name:"firstsocket"},{name:"secondsocket"}]; array,

then you would be able to close a socket connection by doing;

io.sockets.sockets[socketlist[req.socketname].socket_id].disconnect(true);

Though, I would recommend you to check if

io.sockets.sockets[socketlist[req.socketname].socket_id]

returns undefined before accessing it's disconnect property.

If you try to access disconnect property of an already closed socket, the code above will return undefined and you will have an error thrown saying

"Can't access the property disconnect of undefined"

Final code should be something like this;

if (io.sockets.sockets[socketlist[req.socketname].socket_id]) {
    io.sockets.sockets[socketlist[req.socketname].socket_id].disconnect(true);
}

You can get the socket.id information of a socket on the initial connection to the server.

I'd advise you to move your io decleration out of the route and declare it like this with your socket list;

var io = require('socket.io')(server);
var socketlist = [], first_socket_connected = false;

The server variable should be your express server.

Then, use the code below to receive socket connections and push to your socket list;

io.on("connection", function(socket) {
    socketlist.push({name: first_socket_connected ? "secondsocket" : "firstsocket", id: socket.id});
    first_socket_connected = true;
});
Ad
source: stackoverflow.com
Ad