I am using socket.io, and I want to know how can I remove the client(socket) after a connection is closed. (In fact, I don't know what is going on after a connection is close, will that socket remained there? Should I remove it? Will it take up memory?)
我正在使用socket.io,我想知道如何在关闭连接后删除客户端(套接字)。 (事实上,我不知道连接关闭后发生了什么,那个套接字是否会保留在那里?我应该将其删除吗?它会占用内存吗?)
My code:
socket.No = socketNo++;
io.sockets.on("connection",function(socket){
setInterval(function(){
console.log("Server calling update collection with socket No.",socket.No);
},3000);
//When connection is close()
socket.on("disconnect",function(){
console.log("A user disconnected");
});
})
What happen is that, for example, I disconnect from the server, I find that server is still logging. What can I do so that I can stop it?
发生的事情是,例如,我断开与服务器的连接,我发现服务器仍在记录。我该怎么办才能阻止它呢?
Thanks~
1 个解决方案
#1
1
In the code above, it is setInterval
that is causing the additional logging.
在上面的代码中,导致额外日志记录的是setInterval。
You will need to store off the id returned from setInterval
then clear it using clearInterval
on a disconnect event.
您需要存储从setInterval返回的id,然后在disconnect事件上使用clearInterval清除它。
Something like:
io.sockets.on("connection",function(socket){
var intervalId = setInterval(function(){
console.log("Server calling update collection with socket No.",socket.No);
},3000);
//When connection is close()
socket.on("disconnect",function(){
console.log("A user disconnected");
clearInterval(intervalId);
});
})
Other than that, no need to do anything else with the socket on the server side. It will get garbage collected at some point.
除此之外,无需对服务器端的套接字执行任何其他操作。它会在某个时刻收集垃圾。
#1
1
In the code above, it is setInterval
that is causing the additional logging.
在上面的代码中,导致额外日志记录的是setInterval。
You will need to store off the id returned from setInterval
then clear it using clearInterval
on a disconnect event.
您需要存储从setInterval返回的id,然后在disconnect事件上使用clearInterval清除它。
Something like:
io.sockets.on("connection",function(socket){
var intervalId = setInterval(function(){
console.log("Server calling update collection with socket No.",socket.No);
},3000);
//When connection is close()
socket.on("disconnect",function(){
console.log("A user disconnected");
clearInterval(intervalId);
});
})
Other than that, no need to do anything else with the socket on the server side. It will get garbage collected at some point.
除此之外,无需对服务器端的套接字执行任何其他操作。它会在某个时刻收集垃圾。