原生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 })
  })
}
相关推荐
一颗青果18 小时前
HTTP协议详解
linux·网络·网络协议·http
广州灵眸科技有限公司21 小时前
瑞芯微(EASY EAI)RV1126B CAN使用
linux·网络·单片机·嵌入式硬件
cici158741 天前
C#实现三菱PLC通信
java·网络·c#
专业开发者1 天前
经 Nordic 实测:蓝牙长距离传输
网络·物联网
zfj3211 天前
top 命令中的 wa (IO wait) 指标,理论上几乎完全是由磁盘IO(包括swap)引起的,而不是网络IO
linux·网络·top·iowait
Xの哲學1 天前
Linux网卡注册流程深度解析: 从硬件探测到网络栈
linux·服务器·网络·算法·边缘计算
Violet_YSWY1 天前
桥接网络、net、仅宿主机三者区别
网络
携欢1 天前
POrtSwigger靶场之Exploiting XXE using external entities to retrieve files通关秘籍
网络·安全·github
xian_wwq1 天前
【学习笔记】OSI安全架构体系
网络·笔记·学习
heartbeat..1 天前
Servlet 全面解析(JavaWeb 核心)
java·网络·后端·servlet