1. 程式人生 > 實用技巧 >Node.js(3)通訊

Node.js(3)通訊

1websocket

安裝庫

全域性安裝 -g

npm install nodejs-websocket -g

  

sever.js

var ws = require("nodejs-websocket");
console.log("Connecting ...");

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

    conn.on("text",function(str){
        //服務端列印接收到的資料
        console.log("News:" + str);
        //接收到的資料打上標記“Server-”,再發送回客戶端
        conn.sendText("Server-"+str);
    });

    conn.on("close",function(code,reason) {
        console.log("Disconnected.");
    });

    conn.on("error",function(code,reason) {
        console.log("Error.")
    });
}).listen(8848);

console.log("Server runing!");

  

web.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Game1 Test Demo</title>
</head>

<body>

    <div id="mess">正在連線...</div>
    <div>
        <button id="state1" >第一重</button>
        <button id="state2">第二重</button>
        <button id="state3">第三重</button><br><br>
        <a> 已傳送:</a>
        <a id="sendnews"></a><br>
        <a>已接收:</a>
        <a id="receivenews"></a>
    </div>

    <script>
        var mess = document.getElementById("mess");
        if(window.WebSocket){
            //這裡修改為本機IP地址
            var ws = new WebSocket('ws://127.0.0.1:8848');

            ws.onopen = function(e){
                console.log("連線伺服器成功");
                mess.innerHTML = "連線成功"
                ws.send("TestClient");
            }

            ws.onclose = function(e){
                console.log("伺服器關閉");
                mess.innerHTML = "伺服器關閉"
            }

            ws.onerror = function(){
                console.log("連接出錯");
                mess.innerHTML = "連接出錯"
            }

            //收到伺服器資料後的回撥函式
            ws.onmessage = function(e){
                document.getElementById("receivenews").innerHTML=e.data;
            }

            //設定點選事件
            document.getElementById("state1").onclick = function(e){
                ws.send("昨夜西風凋碧樹,獨上西樓,望盡天涯路。");
                document.getElementById("sendnews").innerHTML="昨夜西風凋碧樹,獨上西樓,望盡天涯路。"
            }
            document.getElementById("state2").onclick = function(e){
                ws.send("衣帶漸寬終不悔,為伊消得人憔悴。");
                document.getElementById("sendnews").innerHTML="衣帶漸寬終不悔,為伊消得人憔悴。"
            }
            document.getElementById("state3").onclick = function(e){
                ws.send("眾裡尋他千百度,驀然回首,那人卻在燈火闌珊處。");
                document.getElementById("sendnews").innerHTML="眾裡尋他千百度,驀然回首,那人卻在燈火闌珊處。"
            }
        }
    </script>
</body>

</html>