原生websocket简单介绍

文章目录

websocket

用于客户端与服务端双向通信的工具


使用

javascript 复制代码
//node
const ws = require('ws');
const app = express();
app.use(cors());
const server = http.createServer(app);
const wss = new ws.Server({ server });

wss.on('connection', (ws) => {
  //初始化
  cilentInit(ws);
  //事件处理
  ws.on('message', (data) => {
    solveMessage(ws, data);
  });
  //结束
  ws.on('close', () => {
    cilentLeave(ws);
  });
});

//web建立连接
ws = new WebSocket(url)
//发送消息
ws.send(data)

原生websocket仅提供了较为简单的机制(如下)

typescript 复制代码
// 1. 连接成功
ws.onopen = () => ws.send('hello')

// 2. 收到消息
ws.onmessage = (e) => console.log(e.data)

// 3. 异常
ws.onerror = (e) => console.error(e)

// 4. 关闭
ws.onclose = (e) => console.log('code=', e.code)

其中前半部分是事件,后面是执行的动作

ws.send主动向服务器发送数据

问题

  1. 原生api发送数据没有timesetoutpromise等,即发送数据后想要等待服务器消息的机制,与超时等需要自己实现
  2. 需要手动对发送的消息进行分类如使用type参数

简单封装

  1. 实现异步机制
  2. 能够分发事件监听与随时去除
typescript 复制代码
private pendingPromises = new Map<string, { resolve: Function; reject: Function }>()

waitForMessage(type: string, timeout = 10000): Promise<any> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      this.pendingPromises.delete(type)
      reject(new Error(`等待消息类型 "${type}" 超时`))
    }, timeout)
    this.pendingPromises.set(type, { resolve: (data) => { clearTimeout(timer); resolve(data) }, reject })
  })
}
相关推荐
阿米亚波1 小时前
【EVE-NG 实战】防火墙基础(VLAN · VRRP · NAT · ACL · 静态路由)
运维·网络·笔记·网络协议·计算机网络·网络安全·运维开发
零意@1 小时前
海光平台debian11的系统,打开pstore功能和验证功能
网络
blueman88881 小时前
qt5-serialbus详细解析
开发语言·网络·qt
学究天人2 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷6)
网络·算法·数学建模·动态规划·几何学·图论·拓扑学
tiantianuser2 小时前
NVME-oF IP 设计2 :设计之前的调研!
网络·网络协议·rdma·roce v2·nvme of
星恒讯工业路由器2 小时前
工业无线通信选型常见问题解答
网络·信息与通信·无线ap·设备选型·工业无线通信·防爆无线设备·4g/5g路由器
智慧光迅AINOPOL3 小时前
校园全光网建设成本对比:全光网取代传统校园网建设成本分析
网络·全光网解决方案·全光网·校园全光网·校园全光网解决方案
2401_873479403 小时前
如何识别代理IP和伪装流量?用IP情报工具三步穿透住宅代理伪装
网络·数据库·网络协议·tcp/ip·ip
s09071363 小时前
深入解析 Sensor Hub Transport Protocol (SHTP) 协议
网络·协议·传感器·shtp
STDD3 小时前
Traefik 中间件深度配置:限流、认证、IP 白名单与错误页面定制
网络协议·tcp/ip·中间件