前端如何使用 WebSocket API 连接到 NestJS 的 WebSocket Gateway?

解读

这道题在国内面试中高频出现,考察的是“前后端 WebSocket 通道如何真正跑通”。
很多候选人能背出 @WebSocketGateway() 装饰器,却说不清:

  1. 网关到底监听哪一端口、哪一路径;
  2. 前端该用 ws:// 还是 wss://,如何带鉴权;
  3. 跨域、Nginx 转发、公司网关(如阿里 MSE、腾讯云 API 网关)对 WebSocket 升级头的影响;
  4. 断线重连、心跳、二进制传输选型。
    面试官希望听到“端到端可落地的细节”,而不是“我引了 socket.io 就完事了”。

知识点

  1. NestJS 两种 WebSocket 模式
    • 原生 ws 库:@WebSocketGateway() 默认走 ws 协议,端口同 HTTP(默认 80/443),路径 /;
    • Socket.IO:@WebSocketGateway({ transports: ['websocket', 'polling'] }),自带房间、广播、降级。
  2. 网关类生命周期
    afterInit → handleConnection → handleDisconnect;通过 @SubscribeMessage() 收消息。
  3. 前端连接字符串
    • 原生 WebSocket:new WebSocket('wss://api.xxx.com/socket');
    • Socket.IO:io('https://api.xxx.com', { path: '/socket.io', transports: ['websocket'] })。
  4. 鉴权四法
    • 子协议头 Sec-WebSocket-Protocol: Bearer.xxx;
    • 查询参数 ?token=xxx(国内最常见,网关层好做日志);
    • 首次 HTTP 握手阶段带 Cookie(需同域);
    • 双通道:REST 登录后返回一次性 wsTicket,再拼到 URL。
  5. 国内运维痛点
    • SLB/ALB 必须开 60s 空闲超时,否则 504;
    • Nginx 需显式配 proxy_http_version 1.1 + proxy_set_header Upgrade $http_upgrade;
    • 公司统一网关(Kong、APISIX)要开 ws 插件并允许 Connection: upgrade。
  6. 断线重连与心跳
    前端 setTimeout 发 ping,服务端 pong;超过 3 次无响应执行 ws.reconnect()。
  7. TypeScript 类型安全
    共享 dto/socket-events.ts,前端用 socket.io-client 的 TypedEmitter,实现“端到端类型对齐”,国内大厂代码审查必查。

答案

下面给出一套在“阿里云平台 + 公司 SLB + Nginx + NestJS”生产环境跑通的最小闭环,前端用原生 WebSocket,方便候选人直接搬到简历项目。

  1. NestJS 网关(TypeScript)
// events.gateway.ts
import {
  WebSocketGateway,
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  MessageBody,
  ConnectedSocket,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Socket } from 'ws';

@WebSocketGateway({
  path: '/socket',
  cors: { origin: ['https://www.xxx.com', 'https://admin.xxx.com'] },
})
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  private logger = new Logger('EventsGateway');

  handleConnection(client: Socket, @ConnectedSocket() socket: any) {
    // 从子协议头拿 token
    const proto = socket.protocol; // 'Bearer.xxx'
    const token = proto?.replace('Bearer.', '');
    try {
      const user = this.validate(token); // 复用 JWT 逻辑
      (client as any).uid = user.uid;   // 挂到连接对象
      this.logger.log(`connected ${user.uid}`);
    } catch {
      client.close(1008, 'Invalid Token');
    }
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`disconnected ${(client as any).uid}`);
  }

  @SubscribeMessage('ping')
  handlePing(@MessageBody() data: any, @ConnectedSocket() client: Socket) {
    client.send(JSON.stringify({ event: 'pong', ts: Date.now() }));
  }

  // 业务消息示例
  @SubscribeMessage('chat')
  handleChat(@MessageBody() dto: { msg: string }, @ConnectedSocket() client: Socket) {
    return { event: 'chat', data: { from: (client as any).uid, msg: dto.msg } };
  }
}
  1. 前端连接代码(Vue3 + Vite,国内主流)
// src/composables/useWs.ts
import { onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';

let ws: WebSocket | null = null;
let reconnectTimer: number | null = null;
const RECONNECT_DELAY = 5000;

export function useWs() {
  const connect = (token: string) => {
    if (ws) return;
    const protocol = `Bearer.${token}`;
    ws = new WebSocket('wss://api.xxx.com/socket', protocol);

    ws.onopen = () => {
      console.log('[ws] connected');
      if (reconnectTimer) {
        clearTimeout(reconnectTimer);
        reconnectTimer = null;
      }
    };

    ws.onmessage = (e) => {
      const payload = JSON.parse(e.data);
      if (payload.event === 'chat') {
        // 抛到 Pinia 或 EventBus
        console.log(payload.data);
      }
    };

    ws.onclose = (ev) => {
      console.warn('[ws] closed', ev.code);
      ws = null;
      if (ev.code !== 1000) {
        reconnectTimer = window.setTimeout(() => connect(token), RECONNECT_DELAY);
      }
    };

    ws.onerror = () => ElMessage.error('网络异常,正在重连…');
  };

  const send = (event: string, data: any) => {
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ event, data }));
    }
  };

  onBeforeUnmount(() => {
    ws?.close(1000);
  });

  return { connect, send };
}
  1. Nginx 配置(运维统一维护)
map $http_upgrade $connection_upgrade {
  default upgrade;
  '' close;
}

server {
  listen 443 ssl http2;
  server_name api.xxx.com;

  ssl_certificate     /etc/ssl/xxx.crt;
  ssl_certificate_key /etc/ssl/xxx.key;

  location /socket {
    proxy_pass http://nest-service:3000;   # K8s service 名
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_read_timeout 3600s;              # 阿里云 SLB 默认 60s,这里兜底
  }
}
  1. 本地开发联调
# 后端
npm run start:dev

# 前端
vite --https --strictPort 4433

浏览器访问 https://localhost:4433,WebSocket 地址 wss://localhost:3000/socket,Chrome DevTools → Network → WS 可看到 101 Switching Protocols。

拓展思考

  1. 如果公司强制走 Socket.IO,如何做到“房间级”权限隔离?
    答:在 handleConnection 阶段把用户加入 client.join(uid),业务消息用 this.server.to(uid).emit(),避免广播泄露。
  2. 万级并发场景,单 Pod 内存飙高,如何横向扩展?
    答:网关无状态,用 Redis Adapter(@socket.io/redis-adapter)做多节点消息同步;K8s HPA 按 CPU 75% 扩容;SLB 开会话保持禁用,避免粘包。
  3. 弱网环境下,如何降低 30% 流量?
    答:启用 perMessageDeflate 压缩;对二进制场景用 msgpack 替代 JSON;心跳包改为 60s 一次,结合服务端 pingTimeout 配置。
  4. 面试常问:WebSocket 与 gRPC stream 选型?
    答:对内高吞吐、强类型用 gRPC stream(HTTP/2 多路复用);对外浏览器、防火墙不可控用 WebSocket;国内小程序只支持 TCP/TLS,WebSocket 是唯一选择。