当前位置: 首页 > 工具软件 > ws-node-demo > 使用案例 >

node字典-websocket 服务端与客户端demo

越勇锐
2023-12-01

客户端

var ws;
 
let isconnected = false;
function reconnect() {
    ws = new WebSocket('ws://124.222.15.231:8001');
    ws.onopen = function (e) {
        isconnected = true;
        console.log("连接服务器成功");
        // 向服务器发送消息
        ws.send("what`s your name?");
    }
    ws.onclose = function (e) {
        console.log("服务器关闭");
        isconnected = false;
    }
    ws.onerror = function () {
        isconnected = false;
        console.log("连接出错");
    }
    // 接收服务器的消息
    ws.onmessage = function (e) {
        isconnected = true;
        let message = "message:" + e.data + "";
        console.log(message);
    

    }
}


setInterval(function () {
    if (!isconnected) {
        return reconnect();
    }
    ws.send("keep live");
}, 9000)

服务器端

var ws = require("nodejs-websocket");
console.log("开始建立连接...")
const clients = {}
var wsserver = ws.createServer(function (conn) {
    let name = new Date().getTime() + "c";
    clients[name] = conn;

    conn.on("text", function (str) {
        console.log("message:" + str)
        conn.sendText("Hello " + name);
 
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
        delete clients[name]
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
        delete clients[name]
    });

}).listen(8001)
console.log("WebSocket建立完毕")
 

 类似资料: