admin管理员组文章数量:1334342
Following instruction from my previous question, I now have an array of connected users in socket.io. My problem (which I was warned of in the answer) is that sockets stay in this array even after the browser has disconnected.
I tried removing sockets from the array in a socket.on('disconnect'
function, but there is still a delay of ~1 minute between when the browser disconnects and socket.io triggers the disconnect.
What is the best way to "test" a socket to see if its actually alive? I am tempted to try to send a message and catch any errors, but I feel like there is a more elegant solution.
Following instruction from my previous question, I now have an array of connected users in socket.io. My problem (which I was warned of in the answer) is that sockets stay in this array even after the browser has disconnected.
I tried removing sockets from the array in a socket.on('disconnect'
function, but there is still a delay of ~1 minute between when the browser disconnects and socket.io triggers the disconnect.
What is the best way to "test" a socket to see if its actually alive? I am tempted to try to send a message and catch any errors, but I feel like there is a more elegant solution.
Share Improve this question edited May 23, 2017 at 11:50 CommunityBot 11 silver badge asked Mar 13, 2013 at 20:18 MrGlassMrGlass 9,26217 gold badges66 silver badges92 bronze badges 1-
2
you could try reducing the
close timeout
, see stackoverflow./questions/7192747/…, default is 60s. – Pascal Belloncle Commented Mar 13, 2013 at 20:31
3 Answers
Reset to default 4Solution on how to test if "socket is still open"
if(socket.readyState === socket.OPEN)
{
}
Why it works:
readyState = The current state of the connection; this is one of the Ready state constants. Read only.
"the Ready state constants"
CONNECTING 0: The connection is not yet open.
OPEN 1: The connection is open and ready to municate.
CLOSING 2: The connection is in theprocess of closing.
CLOSED 3: The connection is closed or couldn't be opened.
https://developer.mozilla/en-US/docs/Web/API/WebSocket
I had an error in my disconnect handler. What I ended up using:
socket.on('disconnect', function() {
users.splice(users.indexOf(socket), 1);
});
socket.on('end',function(){
//your code
})
or
socket.on('error',function(err){
//in case of any errors
})
The disconnect event wont fire until all the clients has been disconnected!
本文标签: javascriptTest if socket is still openStack Overflow
版权声明:本文标题:javascript - Test if socket is still open - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742338075a2456032.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论