1. 程式人生 > 其它 >nodejs 實現即時通訊

nodejs 實現即時通訊

1. 建立一個空資料夾, 安裝包 
npm init -y
npm i nodejs-websocket --save

2. 服務端程式碼, 在當前目錄建立 app.js 檔案

var ws = require("nodejs-websocket");
console.log("開始建立連線...");

const socketPool = [];

const socket = ws.createServer(function (conn) {
  conn.on("text", function (str) {
    console.log(str);
    const params = JSON.parse(str);
    console.log(params);
    const { type, from, to, message } 
= params; // 建立連線通知 if (type === 1) { const s = { name: from, conn, }; socketPool.push(s); console.log(socketPool); } else if (type === 2) { const index = socketPool.findIndex((i) => i.name === to); if (index >= 0) { socketPool[index].conn.sendText( JSON.stringify({ from: to, to: from, message, }) ); } } }); conn.on(
"close", function (code, reason) { console.log("關閉連線", reason); }); conn.on("error", function (code, reason) { console.log("異常關閉"); }); }); socket.listen(8001, () => { console.log("WebSocket建立完畢"); });

3. 使用者端1, 在任意位置建立 html1

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>user-張三</title>
    <style>
      * {
        margin: 
0; padding: 0; box-sizing: border-box; } .message_box { width: 600px; height: 100vh; background-color: pink; display: flex; flex-direction: column; } .msg_list { flex: 1; overflow-y: auto; } .btn_box { flex: 0 0 40px; background-color: red; display: flex; } .btn_box input { width: 540px; height: 100%; } .btn_box .btn { flex: 1; color: #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="message_box"> <div class="msg_list"></div> <div class="btn_box"> <input type="text" id="ipt" /> <div class="btn" id="btn">傳送</div> </div> </div> <script> const btn = document.querySelector("#btn"); const msgList = document.querySelector(".msg_list"); let ws; if (window.WebSocket) { ws = new WebSocket("ws://127.0.0.1:8001"); ws.onopen = function (e) { ws.send( JSON.stringify({ type: 1, from: "zs", }) ); }; ws.onclose = function (e) { console.log("伺服器關閉"); }; ws.onerror = function () { console.log("連接出錯"); }; ws.onmessage = function (e) { data = JSON.parse(e.data); const div = document.createElement("div"); div.innerText = `收到${data.from}的訊息 ---------- ${data.message}`; msgList.append(div); }; btn.addEventListener("click", (ev) => { const ipt = document.querySelector("#ipt"); const v = ipt.value; ws.send( JSON.stringify({ from: "zs", to: "ls", type: 2, message: v, }) ); ipt.value = ""; }); } </script> </body> </html>

 

4. 任意位置建立 HTML2

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>user-李四</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      .message_box {
        width: 600px;
        height: 100vh;
        background-color: pink;
        display: flex;
        flex-direction: column;
      }

      .msg_list {
        flex: 1;
        overflow-y: auto;
      }

      .btn_box {
        flex: 0 0 40px;
        background-color: red;
        display: flex;
      }

      .btn_box input {
        width: 540px;
        height: 100%;
      }

      .btn_box .btn {
        flex: 1;
        color: #fff;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    </style>
  </head>
  <body>
    <div class="message_box">
      <div class="msg_list"></div>
      <div class="btn_box">
        <input type="text" id="ipt" />
        <div class="btn" id="btn">傳送</div>
      </div>
    </div>

    <script>
      const btn = document.querySelector("#btn");
      const msgList = document.querySelector(".msg_list");
      let ws;
      if (window.WebSocket) {
        ws = new WebSocket("ws://127.0.0.1:8001");

        ws.onopen = function (e) {
          ws.send(
            JSON.stringify({
              type: 1,
              from: "ls",
            })
          );
        };
        ws.onclose = function (e) {
          console.log("伺服器關閉");
        };
        ws.onerror = function () {
          console.log("連接出錯");
        };

        ws.onmessage = function (e) {
          data = JSON.parse(e.data);
          const div = document.createElement("div");
          div.innerText = `收到${data.from}的訊息 ---------- ${data.message}`;
          msgList.append(div);
        };

        btn.addEventListener("click", (ev) => {
          const ipt = document.querySelector("#ipt");
          const v = ipt.value;
          ws.send(
            JSON.stringify({
              from: "ls",
              to: "zs",
              type: 2,
              message: v,
            })
          );
          ipt.value = "";
        });
      }
    </script>
  </body>
</html>

5. 啟動流程

在app.js目錄, cmd 執行 node  app.js  提示  

WebSocket建立完畢 說明長連線建立完成   已不同的瀏覽器分別開啟 html1 和 html2 就能愉快的傳送訊息了