Closed SokuRitszZ closed 10 months ago
在官方文档中,建立一个 socket 服务,其实就相当于建立一个网关。
pnpm i --save @nestjs/websockets @nestjs/platform-socket.io socket.io
// 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 {
}
}
使用 postman。
先注册/登陆获取合法 jwt,然后创建 socket.io
连接,在 headers 中加入 x-jwt=***,然后点击连接,可以发现连接成功。
如果使用不合法的 jwt 测试,可以发现会连接成功之后会直接断开连接,这样相当于实现了 jwt 鉴权。
改用/ws
来走 websocket 通道,不占用特定端口 #36
如果要把后端服务部署到服务器上,服务器上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;
}