Node.js客户端连接安全关闭

时间:2019-11-08 02:36:51

标签: html node.js websocket

我是Nodejs的新手,我正在使用nodejs websocket尝试与客户端应用程序进行通信。我需要帮助的是在不使我的nodejs服务器崩溃的同时安全地关闭客户端连接。更具体地说,在nodejs服务器将消息发送回客户端之前,先检查是否存在连接。

客户端应用代码

function tuneIn(){
    connection = new WebSocket('ws://localhost:8001');
    connection.onmessage = function (event) { 
        document.getElementById('currentScore').innerHTML=event.data;
    };
}

tuneInButton.addEventListener('click', tuneIn);

function tuneOut(){
    connection.close();
}
tuneOutButton.addEventListener('click', tuneOut);

Node js代码

var ws = require("nodejs-websocket");

var server = ws.createServer(function (conn) {

    console.log("New connection");
    var score = 0;
    setInterval(function(){ 
        conn.sendText(score.toString());
        score++; 
    }, 1000);


    conn.on("disconnect", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(8001)

1 个答案:

答案 0 :(得分:0)

为什么当网络套接字断开连接时,您不只是停止间隔计时器?

const ws = require("nodejs-websocket");

const server = ws.createServer(function (conn) {

    console.log("New connection");
    let score = 0;
    let timer = setInterval(function(){ 
        conn.sendText(score.toString());
        score++; 
    }, 1000);


    conn.on("disconnect", function (code, reason) {
        clearInterval(timer);
        console.log("Connection closed")
    })
}).listen(8001)