gpt4 book ai didi

javascript - 测试套接字是否仍然打开

转载 作者:行者123 更新时间:2023-11-30 05:50:07 25 4
gpt4 key购买 nike

遵循我的 previous question 的指示,我现在在 socket.io 中有一组已连接的用户。我的问题(我在回答中被警告过)是即使在浏览器断开连接后套接字仍保留在此数组中。

我尝试在 socket.on('disconnect' 函数中从数组中删除套接字,但在浏览器断开连接和 socket.io 触发断开连接之间仍有约 1 分钟的延迟.

“测试”套接字以查看其是否真正存在的最佳方法是什么?我很想尝试发送消息并捕获任何错误,但我觉得有更优雅的解决方案。

最佳答案

关于如何测试“socket is still open”的解决方案

if(socket.readyState === socket.OPEN)
{
}

为什么有效:

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 communicate.
CLOSING 2: The connection is in theprocess of closing.
CLOSED 3: The connection is closed or couldn't be opened.

https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

关于javascript - 测试套接字是否仍然打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15395662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com