简体   繁体   中英

How can i disconnect a socket both server and client side in socket.io 1.0

Consider the following:

//client side: 
var socket = io('http://localhost');
//disconnecting client side 5 seconds after connecting
setTimeout(function(){
    socket.disconnect();
},5000);

//Server side:
var io = ......
io.on('connection', function (socket) {
    setInterval(function(){
        console.log(socket.id);//this will continue outputting the socket.id forever.
    },1000);
});

Now my question is how will i disconnect from both server/client as the client approach alone doesn't seem to work.

Thanks.

As for your actual question: no need to do anything, the client is disconnected from the server. However the problem you're experiencing is not that the client is not disconnected, but that you have created an interval. In JavaScript a setInterval callback will continue to run until you tell it to stop .

Thus the solution is to tell it to stop when the client disconnects:

//Server side:
var io = ......
io.on('connection', function (socket) {
    var intervalId = setInterval(function(){
        console.log(socket.id); //this will continue outputting the socket.id until clearInterval() is called
    },1000);

    socket.on('disconnect', function() {
        clearInterval(intervalId);
    });
});

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