博客
关于我
nodejs 开发websocket 笔记
阅读量:792 次
发布时间:2023-02-16

本文共 2674 字,大约阅读时间需要 8 分钟。

使用Node.js开发WebSocket消息分发系统

WebSocket是一种高效的网络通信协议,基于HTTP协议的长连接机制,相比传统的Comet技术,它更适合处理大量实时数据传输需求。WebSocket的事件驱动特性与Node.js的内置事件机制高度契合,使得开发高性能实时应用变得更加简单高效。

在客户端调用

WebSocket客户端通过WebSocket接口与服务端建立连接,主要操作包括消息接收、连接状态变化处理以及消息发送等。以下是常见的事件处理方式:

  • 消息接收:当客户端收到消息时,触发message事件。
  • 连接握手完成:连接建立后触发open事件。
  • 连接关闭:连接异常断开或正常释放时,触发close事件。
  • 错误处理:连接出现异常时,触发error事件。
  • 消息发送:通过ws.send()方法向服务端发送消息,参数可为字符串、Buffer或其他数据类型。
  • // 示例代码let url = `ws://127.0.0.1:3000/socket?id=${id}&name=${name}&teamId=${teamId}`;let ws = new WebSocket(url);ws.addEventListener('message', this.message.bind(this));ws.addEventListener('open', this.open.bind(this));ws.addEventListener('close', this.close.bind(this));ws.addEventListener('error', this.error.bind(this));ws.send('消息发送');

    服务端接收调用

    服务端通过Node.js处理HTTP升级请求,完成WebSocket协议握手流程。以下是关键步骤解析:

  • 接收客户端请求:服务端首先接收客户端的HTTP请求头,检查升级字段upgrade: websocketconnection: upgrade,确认客户端支持WebSocket协议。
  • 验证Sec-WebSocket-Key:服务端接收客户端发送的Sec-WebSocket-Key值,通过SHA-1算法验证并生成响应头字段,返回计算后的Sec-WebSocket-Key值。
  • 处理升级事件:在HTTP升级完成后,服务端创建WebSocket对象,绑定已建立的socket连接,并通过socket.setNoDelay(true)优化数据传输效率。
  • 消息接收与处理:在收到客户端发送的消息时,触发message事件,服务端可通过ws.send()方法向客户端发送响应或处理后续逻辑。
  • // 示例代码const WebSocket = require('ws');let ctx = {};let ws = ctx.websocket;ws.on('message', this.EVENT_MESSAGE.bind(this));ws.on('error', this.EVENT_ERROR.bind(this));ws.on('close', this.EVENT_CLOSE.bind(this));ws.on('timeout', this.EVENT_ERROR.bind(this));

    后期开发中的数据库集成

    在WebSocket应用的后续优化中,引入了Redis和MSSQL进行数据存储操作,提升了系统的持久化能力和数据处理能力。

  • Redis集成
    • Redis具备自动重试连接机制,不需要额外处理重新连接逻辑。
    • 通过自定义重试策略优化连接丢失问题,确保数据存储的高可用性。
  • // 示例代码this.client = redis.createClient({  host: host,  port: port,  retry_strategy(options) {    if (options.error.code === 'ECONNREFUSED') {      console.log('连接被拒绝');      Log.error('连接被拒绝');    }    if (options.times_connected > 10) {      console.log('重试连接超过十次');      Log.error('重试连接超过十次');    }    return Math.max(options.attempt * 100, 3000);  }});
    1. MSSQL集成
      • 使用new sql.ConnectionPool创建数据库连接池。
      • 在数据库操作完成后,确保通过sql.close()关闭连接,避免二次连接失败问题。
    2. // 示例代码const sql = require('mssql');class XX {  connect() {    return new sql.ConnectionPool(this.config).connect();  }  async query(str) {    let pool;    let result;    try {      pool = await this.connect();      result = await pool.request().query(str);    } catch (e) {      console.log('数据库链接错误:' + e.message);      Log.error('数据库链接错误:' + e.message);      return Promise.reject(e.message).catch(str => {        this.emit('DBError', str);      });    }    let rows = result.recordset;    let data = [];    if (result.recordsets.length) {      data = result.recordsets[0];    }    sql.close();    return Promise.resolve(toJson(data));  }}

      通过以上优化,WebSocket消息分发系统的性能和可靠性得到了显著提升,数据库集成后进一步增强了系统的数据处理能力。

    转载地址:http://ztjfk.baihongyu.com/

    你可能感兴趣的文章
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>