You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在NestJS中使用ws库替代socket.io消费指定WSS端点遇阻求指导

在NestJS中用ws库连接Binary WebSocket端点的解决方案

1. 安装必要依赖

先安装ws库和NestJS的WebSocket相关依赖:

npm install ws @nestjs/websockets @nestjs/platform-ws

2. 实现WebSocket客户端服务

创建一个NestJS服务来封装WebSocket连接、消息收发和生命周期管理:

import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import * as WebSocket from 'ws';

@Injectable()
export class BinaryWsClient implements OnModuleInit, OnModuleDestroy {
  private wsClient: WebSocket;

  onModuleInit() {
    // 初始化连接到目标端点
    this.wsClient = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');

    // 连接成功回调
    this.wsClient.on('open', () => {
      console.log('已连接到Binary WebSocket服务');
      // 示例:发送获取服务器时间的请求
      this.sendRequest({ time: 1 });
    });

    // 接收消息回调
    this.wsClient.on('message', (rawData) => {
      const response = JSON.parse(rawData.toString());
      console.log('收到响应:', response);
      // 这里处理业务逻辑
    });

    // 错误监听
    this.wsClient.on('error', (err) => {
      console.error('WebSocket错误:', err);
    });

    // 连接关闭监听
    this.wsClient.on('close', (code, reason) => {
      console.log(`连接关闭: 状态码 ${code}, 原因 ${reason.toString()}`);
    });
  }

  // 封装发送请求的方法
  sendRequest(payload: object) {
    if (this.wsClient.readyState === WebSocket.OPEN) {
      this.wsClient.send(JSON.stringify(payload));
    } else {
      console.error('WebSocket连接未处于打开状态,无法发送请求');
    }
  }

  onModuleDestroy() {
    // 模块销毁时关闭连接
    if (this.wsClient) {
      this.wsClient.close();
    }
  }
}

3. 在模块中注册服务

把上面的服务加入到你的业务模块的providers中:

import { Module } from '@nestjs/common';
import { BinaryWsClient } from './binary-ws.client';

@Module({
  providers: [BinaryWsClient],
  exports: [BinaryWsClient], // 如果其他模块需要注入该服务,就加上这行
})
export class YourBusinessModule {}

4. 常见问题排查

  • 连接失败:检查网络连通性,确认app_id=1089是否可用(这是官方测试ID,正常情况下没问题)
  • 发送请求无响应:确保请求格式符合Binary API的规范,所有请求必须是合法JSON结构
  • 意外断开:可以在close事件中添加重连逻辑,比如延迟几秒后重新初始化连接

内容的提问来源于stack exchange,提问作者Duncan Moiyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 13:50:02