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
就能愉快的发送消息了
posted @   深海里的星星i  阅读(420)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示