Node.js+html5实现WebSocket服务示例

{
  "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();">exitbutton>
    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 + "
"
; 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 + "
"
; }; 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>

你可能感兴趣的:(node.js,html5,websocket)