JavaScript:服务器脱机时关闭WebSocket

时间:2017-08-08 11:52:18

标签: javascript websocket

我使用WebSockets在ESP8266(服务器,使用arduinoWebSockets library)和网页(客户端)上运行的JavaScript之间进行通信。

我想在ESP和浏览器之间的连接丢失时通知用户 要检查连接是否仍然有效,客户端会发送一个" p"消息每秒,服务器只是回应它。如果客户端在一秒钟内没有收到此回音,则会关闭连接(WS.close();)。 WS.onclose事件设置超时以建立新连接。

此方法有效,但问题是当互联网连接丢失或服务器重置时,WS.close()无法按预期工作。
它仅在WebSocket.CLOSING状态下花费60秒,然后超时,将onclose事件称为太晚一分钟。

当服务器脱机时,有没有办法立即断开WebSocket连接?

let WS;
let WStimeout;
let pingInterval;

startWS();

function startWS() {
    console.log("Start WebSocket");
    WS = new WebSocket('ws://' + location.hostname + ':81/');
    WS.onopen = function () {
        pingInterval = setInterval(ping, 1000);
    };
    WS.onerror = function (err) {
        console.log('WebSocket Error ', err);
    };
    WS.onclose = function (ev) {
        console.log("WebSocket Closed ", ev);
        clearInterval(pingInterval);
        // ... let user know that the connection is lost
        WS = null;  // delete the current WebSocket
        setTimeout(startWS, 5000);  // try connecting to WebSocket server again in 5 seconds
    }
    WS.onmessage = function (ev) {
        clearTimeout(WStimeout);  // server is still online, clear "ping" timeout
        console.log(ev.data);
        // ... handle incoming data
    }
}

function ping() {
    if (!WS || WS.readyState !== WebSocket.OPEN) {
        console.log("Connection not open: " + WS.readyState);
        return;
    }
    WS.send("p");  // send ping to server
    WStimeout = setTimeout(function () {  // if it doesn't respond within a second
        if (WS && WS.readyState === WebSocket.OPEN) {  // and if the connection is still open
            console.error("Ping timed out: closing WebSocket connection ...");
            WS.close();  // close the connection
        }
    }, 1000);
}

输出:

Start WebSocket
p
...
p

* Turned WiFi off and on again *

Ping timed out: closing WebSocket connection ...

Connection not open: 2
... (60 times in total, for 1 minute)
Connection not open: 2

WebSocket Closed  
CloseEvent {isTrusted: true, wasClean: false, code: 1006, reason: "", type: "close", …}

Start WebSocket
p
...

0 个答案:

没有答案