NodeJs 實現簡單WebSocket 即時通信

服務器的實現很簡單,先裝一個nodeJs的模塊,叫nodejs-websocket , 直接在nodeJs命令行中敲入:npm install nodejs-websocket回車就能夠安裝好了,
而後就能夠開始創建服務器了,由於有了nodejs-websocket模塊,因此不少工做都不用咱們本身作,直接調用別人封裝好的方法就好了:
  • 服務端代碼
  • 根據客戶端傳來的消息判斷哪一個是game1,哪一個是game2,保存connection對象。
var ws = require("nodejs-websocket");
console.log("開始創建鏈接...")

var game1 = null,game2 = null , game1Ready = false , game2Ready = false;
var server = ws.createServer(function(conn){
    conn.on("text", function (str) {
        console.log("收到的信息爲:"+str)
        if(str==="game1"){
            game1 = conn;
            game1Ready = true;
            conn.sendText("success");
        }
        if(str==="game2"){
            game2 = conn;
            game2Ready = true;
        }

        if(game1Ready&&game2Ready){
            game2.sendText(str);
        }

        conn.sendText(str)
    })
    conn.on("close", function (code, reason) {
        console.log("關閉鏈接")
    });
    conn.on("error", function (code, reason) {
        console.log("異常關閉")
    });
}).listen(8001)
console.log("WebSocket創建完畢")

【game1代碼】:經過點擊獲取三個框的內容,傳到服務器html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .kuang{text-align: center;margin-top:200px;}
        #mess{text-align: center}
        .value{width: 200px;height:200px;border:1px solid;text-align: center;line-height: 200px;display: inline-block;}
    </style>
</head>
<body>
    <div id="mess">正在鏈接...</div>
    <div class="kuang">
        <div class="value" id="value1">小明小明</div>
        <div class="value" id="value2">啦啦啦</div>
        <div class="value" id="value3">小張小張</div>
    </div>

    <script>
        var mess = document.getElementById("mess");
        if(window.WebSocket){
            var ws = new WebSocket('ws://127.0.0.1:8001');

            ws.onopen = function(e){
                console.log("鏈接服務器成功");
                ws.send("game1");
            }
            ws.onclose = function(e){
                console.log("服務器關閉");
            }
            ws.onerror = function(){
                console.log("鏈接出錯");
            }

            ws.onmessage = function(e){
                mess.innerHTML = "鏈接成功"
                document.querySelector(".kuang").onclick = function(e){
                    var time = new Date();
                    ws.send(time + "  game1點擊了「" + e.target.innerHTML+"」");
                }
            }
        }
    </script>
</body>
</html>

【game2代碼】:獲取服務推送來的消息,而且顯示node

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .kuang{text-align: center;margin-top:200px;}
        #mess{text-align: center}
    </style>
</head>
<body>
    <div id="mess"></div>

    <script>
        var mess = document.getElementById("mess");
        if(window.WebSocket){
            var ws = new WebSocket('ws://127.0.0.1:8001');

            ws.onopen = function(e){
                console.log("鏈接服務器成功");
                ws.send("game2");
            }
            ws.onclose = function(e){
                console.log("服務器關閉");
            }
            ws.onerror = function(){
                console.log("鏈接出錯");
            }

            ws.onmessage = function(e){
                var time = new Date().t.toLocaleDateString();
                mess.innerHTML+=time+"的消息:"+e.data+"<br>"
            }
        }
    </script>
</body>
</html>

運行截圖:
圖片描述web

相關文章
相關標籤/搜索