1. 程式人生 > >NodeJs 實現 WebSocket 即時通訊(簡單版)

NodeJs 實現 WebSocket 即時通訊(簡單版)

 

 

服務端程式碼

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建立完畢")

 

客戶端程式碼:

  傳資料到伺服器

<!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>

  

  接收服務端傳送的資料

<!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();
                mess.innerHTML+=time+"的訊息:"+e.data+"<br>"
            }
        }
    </script>
</body>
</html>

 

來源:https://www.cnblogs.com/axes/p/3586132.html