原生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 })
  })
}
相关推荐
YuMiao1 小时前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Jony_3 天前
高可用移动网络连接
网络协议
chilix3 天前
Linux 跨网段路由转发配置
网络协议
DianSan_ERP5 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅5 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19985 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
2501_946205525 天前
晶圆机器人双臂怎么选型?适配2-12寸晶圆的末端效应器有哪些?
服务器·网络·机器人
linux kernel5 天前
第七部分:高级IO
服务器·网络
数字护盾(和中)5 天前
BAS+ATT&CK:企业主动防御的黄金组合
服务器·网络·数据库
~远在太平洋~5 天前
Debian系统如何删除多余的kernel
linux·网络·debian