github: 库地址

node后端:

interface msgType {
  from: string;
  to: string;
  msg: string;
}
export class Server {
  private ws = require("nodejs-websocket");
  private connections: { nickname: string; con: any }[] = [];
  constructor() {
    this.startServer();
  }
  public send(msg: msgType) {
    const dest = this.connections.find((val) => val.nickname === msg.to);
    if (!dest) return;
    dest.con.send(JSON.stringify(msg));
  }
  public receive() {}
  private startServer() {
    this.ws
      .createServer((conn: any) => {
        let init: boolean = false;
        conn.on("text", (str: string) => {
          const obj = JSON.parse(str) as msgType;
          if (!init) {
            init = true;
            const exist = this.connections.find(
              (val) => val.nickname === obj.from
            );
            if (!exist)
              this.connections.push({ nickname: obj.from, con: conn });
            else exist.con = conn;
            console.log("new connection: " + obj.from);
          }

          this.send(obj);
        });
        conn.on("close", function (code: any, reason: any) {
          console.log(code, reason);
        });
        conn.on("error", function (code: any, reason: any) {
          console.log(code, reason);
        });
      })
      .listen(8080);
  }
  public closeServer() {
    this.connections.forEach((val) => val.con.close());
    this.ws.closeServer();
  }
}

前端:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        height: 100vh;
        width: 100vw;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
      input {
        margin-bottom: 20px;
      }
    </style>
  </head>
  <body>
    <input type="text" id="from" value="" />
    <input type="text" id="to" value="" />
    <input type="text" id="msg" value="hi!" />
    <button onclick="send()">send</button>
    <div id="history"></div>
    <script>
      const ws = new WebSocket("ws://127.0.0.1:8080");
      const history = document.querySelector("#history");
      ws.onopen = () => {
        console.log("open");
      };
      ws.onmessage = (e) => {
        const obj = JSON.parse(e.data);
        history.innerHTML = history.innerHTML +=
          "<br />" + JSON.stringify(obj.msg);
      };
      ws.onclose = () => {
        console.log("close");
      };
      ws.onerror = (e) => {
        console.log(e, "error");
      };
      const user1 = () => {
        from.value = "user1";
        to.value = "user2";
      };
      const user2 = () => {
        from.value = "user2";
        to.value = "user1";
      };

      if (localStorage.getItem("identity")) {
        user2();
      } else {
        user1();
      }
      const send = () => {
        const obj = {
          from: from.value,
          to: to.value,
          msg: msg.value,
        };
        if (!(obj.from && obj.to && obj.msg)) {
          alert("missing value");
          return;
        }
        ws.send(JSON.stringify(obj));
      };
    </script>
  </body>
</html>

 

 posted on 2024-04-02 11:39  laremehpe  阅读(4)  评论(0编辑  收藏  举报