01月04, 2023

WebSocket(2)-WebSocket 实战 - 1

WebSocket 实战 - 1

WebSocket API

WebSocket原生接口API:https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket/WebSocket

首先,无论如何,WebSocket主要的工作内容还是在后端,前端主要是各种事件触发之后要做各种的事情,后端代码这里就不再一一详解了,给大家提供了nodejs的简单后端代码,仅供参考。

后端代码

安装

npm i ws

ws-server.js

const { WebSocketServer } = require("ws");

//创建后台WebSocket服务
function createServer(port) { 
  return new Promise((resolve) => { 
    const wss = new WebSocketServer({ port }, () => { 
      resolve(wss);
    })
  })
}

let count = 0;

async function init(port) { 
  const wss = await createServer(port);
  console.log("原生 WebSocket 服务已经启动,端口号:" + port);
  //连接
  wss.on('connection', (socket) => {
    //接收消息,注意回调函数中的message参数是一个buffer对象
    socket.on('message', (message) => {
      console.log("接收来自前端的信息:" + message);
      if (message.toString() === "hello") {
        socket.send("hello,boy");
      }
      else if (message.toString() === "服务器") {
        socket.send("我在呢!")
      }
      else { 
        socket.send("你好啊,我是后台服务");
      } 
    })
  });

  //每隔3秒钟轮询给每个客户端发送信息
  const timer = setInterval(() => {
    count++;
    wss.clients.forEach(ws => { 
      ws.send(`来自服务器的消息:${count}`);
    })
  }, 3000);

  //后端关闭websocket服务触发
  wss.on('close', (e) => {
    clearInterval(timer);
  });
}

init(9527);

运行

node ws-server.js

前端相关API

const ws = new WebSocket("地址"); // 创建websocket连接,浏览器自动握手

// 事件:握手完成后触发
ws.onopen = function () {
  console.log('连接到了服务器');
};
// 事件:收到服务器消息后触发
ws.onmessage = function (e) {
  console.log(e.data); // e.data:服务器发送的消息
};
// 事件:连接关闭后触发
ws.onclose = function () {
  console.log('连接关闭了');
};

// 发送消息到服务器
ws.send(消息);
// 连接状态:0-正在连接中  1-已连接  2-正在关闭中  3-已关闭
ws.readyState

具体实现

<!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>Document</title>
  </head>
  <body>
    <button id="btnConnect">连接到服务器</button>
    <br />
    <input type="text" id="content" />
    <button id="btnSend">发送消息</button>
    <br />
    <button id="btnClose">关闭连接</button>
  </body>
  <script>
    const btnConnect = document.getElementById("btnConnect");
    const txtContent = document.getElementById("content");
    const btnSend = document.getElementById("btnSend");
    const btnClose = document.getElementById("btnClose");

    let ws = null;

    btnConnect.addEventListener("click", () => {
      ws = new WebSocket("ws://localhost:9527");
      ws.onopen = function () {
        console.log("连接到了后台服务器");
      };
      ws.onclose = function (e) {
        console.log("关闭前端WebSocket");
      };
    });

    btnSend.addEventListener("click", () => {
      let content = txtContent.value;
      ws.send(content);
      ws.onmessage = function (e) {
        console.log(e.data);
      };
    });

    btnClose.addEventListener("click", () => {
      ws.close();
    });

  </script>
</html>

本文链接:http://www.yanhongzhi.com/post/websocket2.html

-- EOF --

Comments