当前位置: 首页 > 工具软件 > koa-websocket > 使用案例 >

websocket:广播

萧波峻
2023-12-01

先看看视频:

websocket 广播效果

 

服务端程序(websocket.js):

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

function now() {
    return new Date().toLocaleString();
}

var n = 0;
var BC = 0;
function broadcast(server) {
    if(BC>0) return;
    BC = setInterval(() => {
        n++;
        server.connections.forEach(function (conn) {
            conn.sendText( "Number:" + n );
        })
    },1000)
}

console.log(now() + "开始建立连接...")
var server = ws.createServer(function(conn){

    console.log(conn.key, "建立连接"+BC)
    clearInterval(BC);
    BC = 0;
    broadcast(server);
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)
console.log(now() + " WebSocket建立完毕")

运行(安装依赖项过程略):

# node websocket.js

客户端程序(mygame.html):

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #mess{text-align: center}
    </style>
</head>
<body>
    <div id="mess">正在连接...</div>
    <script>
        function now() {
            return new Date().toLocaleString();
        }

        var NAME = prompt("请输入花名:");
        var mess = document.getElementById("mess");
        var conn = false;
        if(window.WebSocket){
            var ws = new WebSocket('ws://yourwebsite:8001');

            ws.onopen = function(e){
                conn = true;
                console.log(NAME+"连接服务器成功");
                ws.send(NAME);
            }
            ws.onclose = function(e){
                conn = false;
                mess.innerHTML = now() + "服务器关闭" +"<br>"
                console.log("服务器关闭");
            }
            ws.onerror = function(){
                console.log("连接出错");
            }

            ws.onmessage = function(e){
                mess.innerHTML = now() + ":"+e.data+"<br>"
            }
        }
    </script>
</body>
</html>

通过浏览器打开客户端程序,在多个界面下,看看数据变化的同步效果,以体会websocket的广播功能。

 类似资料: