Board-Game-Bot / backend-nest

这是为 Board Game Bot App 提供的后端平台,旨在提供主要的C端业务后端服务。
0 stars 0 forks source link

后端需求:Socket.io 同步 #34

Closed SokuRitszZ closed 10 months ago

SokuRitszZ commented 10 months ago
SokuRitszZ commented 10 months ago

目标

计划

SokuRitszZ commented 10 months ago

行动

首先见官方文档:

在官方文档中,建立一个 socket 服务,其实就相当于建立一个网关。

1. 安装相关依赖

pnpm i --save @nestjs/websockets @nestjs/platform-socket.io socket.io

2. 编写模块

// socket/module.ts
import { Module } from '@nestjs/common';
import { SocketGateway } from './gateway';

@Module({
  providers: [SocketGateway],
})
export class SocketModule {

}
// socket/gateway.ts
import { OnGatewayConnection, OnGatewayDisconnect, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { JwtService } from '@nestjs/jwt';
import { Inject, Injectable } from '@nestjs/common';

@Injectable()
@WebSocketGateway(
  4567,
  {
    cors: { origin: '*' },
  })
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
    server: Server;

  @Inject()
    jwtService: JwtService;

  handleConnection(client: Socket): any {
    try {
      // success
      const jwt = client.request.headers['x-jwt'] as string;
      this.jwtService.verify(jwt);
    }
    catch{
      // failed
      client.disconnect();
    }
  }

  handleDisconnect(client: Socket): any {

  }
}

3. 测试

使用 postman。

先注册/登陆获取合法 jwt,然后创建 socket.io 连接,在 headers 中加入 x-jwt=***,然后点击连接,可以发现连接成功。

image

如果使用不合法的 jwt 测试,可以发现会连接成功之后会直接断开连接,这样相当于实现了 jwt 鉴权。 image

SokuRitszZ commented 10 months ago

改用/ws来走 websocket 通道,不占用特定端口 #36

SokuRitszZ commented 10 months ago

注意事项

如果要把后端服务部署到服务器上,服务器上nginx需要进行配置,在经过/ws以及/socket.io(需要发送额外的请求来建立连接)的时候,需要进行如下的配置代理转发。

      location /socket.io {
          proxy_pass http://127.0.0.1:3000;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header Host $http_host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
          proxy_read_timeout  36000s;
      }

      location /ws {
          proxy_pass http://127.0.0.1:3000;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header Host $http_host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
          proxy_read_timeout  36000s;
      }