首页 前端知识 Node.js html5实现WebSocket服务示例

Node.js html5实现WebSocket服务示例

2024-04-13 23:04:45 前端知识 前端哥 102 520 我要收藏
{
  "scripts": {
    "dev": "node ws.js",
    "ncc": "ncc build ./ws.js -m -o ./dist/"
  },
  "dependencies": {
    "@vercel/ncc": "^0.36.1",
    "ws": "^8.13.0"
  }
}

const http = require("http");
const fs = require("fs");
const { WebSocket, WebSocketServer } = require("ws");

var fun = function (request, response) {
  var stream = fs.createReadStream("./ws.html", {
    flag: "r",
    encoding: "utf8",
  });
  stream.pipe(response);
};

var server = http.createServer(fun).listen(9091);
var wsServer = new WebSocketServer({ server: server });

wsServer.broadcast = (msg) => {
  wsServer.clients.forEach((client) => {
    if (client.readyState == WebSocket.OPEN) {
      client.send("【广播】" + msg);
      console.log(666.789, wsServer.clients);
    }
  });
};

wsServer.on("connection", (ws, req) => {
  console.log(666.1001, ws, req);

  ws.on("message", (msg) => {
    const msgObj = JSON.parse(msg.toString());
    if (msgObj?.type) {
      if (msgObj.type === "login") {
        ws.userinfo = msgObj.userinfo;
      }
      if (msgObj?.data) {
        const msgStr = ws.userinfo.username + "说:" + msgObj.data.msg;
        console.log(666.10021, msgObj);
        ws.send("服务器[私发]:" + msgStr);
        wsServer.broadcast(msgStr);
      }
    }
  });

  ws.on("close", () => {
    console.log(666.1005, "ws is closed!");
  });
});


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Node.js+html5实现WebSocket服务示例</title>
  </head>
  <body>
    <div id="show"></div>
    <div>
      <input id="message" type="text" style="width: 200px" />
      <button type="button" id="send" onclick="sendMessage();">Send!</button>
      <button type="button" id="send" onclick="exit();">exit</button>
    </div>
    <script>
      var ws = new WebSocket("ws://localhost:9091");

      ws.onopen = (e) => {
        console.log("Connection to server opened" + ws.readyState);

        document.getElementById("show").innerHTML =
          "连接状态:" + ws.readyState + "</br>";

        ws.send(
          JSON.stringify({
            type: "login",
            userinfo: { username: 'asai' + Date.now(), password: "123456" },
          })
        );

        ws.onmessage = (evt) => {
          console.log(666.10002, evt);
          document.getElementById("show").innerHTML += evt.data + "</br>";
        };

        ws.onclose = (evt) => {
          console.log("WebSocketClosed!");
          console.log(evt);
        };
      };

      function sendMessage() {
        var msg = document.getElementById("message").value;
        var msgObj = { type: "message", data: { msg: msg } };
        ws.send(JSON.stringify(msgObj));
        document.getElementById("message").value = "";
      }

      function exit() {
        ws.close();
        console.log("退出啦");
      }
    </script>
  </body>
</html>


转载请注明出处或者链接地址:https://www.qianduange.cn//article/4893.html
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!