简体   繁体   English

我如何在socket.io 1.0中断开服务器和客户端的套接字

[英]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 . 在JavaScript中,setInterval回调将继续运行, 直到您告诉它停止为止

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);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM