当前位置: 首页 > 文档资料 > NestJS 中文文档 >

网关

优质
小牛编辑
129浏览
2023-12-01

网关

There are special components in Nest called Gateways. Gateways help us to create real-time web apps. They are some kind of encapsulated socket.io features adjusted to framework architecture.

Nest中有一个特殊的组件叫网关。他可以帮着我们创建实时的web应用程序。网关是适用于框架结构的封装的scoket.io功能。

import { WebSocketGateway } from '@nestjs/websockets';

@WebSocketGateway()
export class UsersGateway {}

By default - server runs on port 80 and with default namespace. We can easily change those settings:

默认情况下--服务器使用默认命名空间在80端口上运行。我们可以很容易地更改这些设置:

@WebSocketGateway({ port: 81, namespace: 'users' })

Of course - server will run only if UsersGateway is listed in module components array, so we have place it there:

当然--只有UsersGateway在模块组件数组中时,服务器才能运行,所以我们需要按照如下的方式将UsersGateway放置在模块组件数组中。

@Module({
    controllers: [ UsersController ],
    components: [ UsersService, UsersGateway ],
    exports: [ UsersService ],
})

There are three useful events of Gateway:

  • afterInit, which gets as an argument native server socket.io object,
  • handleConnection and handleDisconnect, which gets as an argument native client socket.io object.

网关有三种有用的事件:

  • afterInit, 获取本地服务器scoket.io对象座位参数。
  • handleConnectionhandleDisconnect, 获取本地客户端socket.io对象作为参数。

There are special interfaces, which helps to manage lifecycle hooks:

  • OnGatewayInit
  • OnGatewayConnection
  • OnGatewayDisconnect

有如下三个接口可以帮助我们管理生命周期:

  • OnGatewayInit
  • OnGatewayConnection
  • OnGatewayDisconnect

消息

In Gateway, we can simply subscribe to emitted messages:

在网关中我们可以轻松订阅发出的消息:

import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';

@WebSocketGateway({ port: 81, namespace: 'users' })
export class UsersGateway {
    @SubscribeMessage('drop')
    handleDropMessage(sender, data) {
        // sender is a native socket.io client object
    }
}

And from client side:

从客户端接收如下:

import * as io from 'socket.io-client';
const socket = io('http://URL:PORT/');
socket.emit('drop', { msg: 'test' });

@WebSocketServer()

If you want to assign to chosen property socket.io native server instance, you could simply decorate it with @WebSocketServer() decorator.

如果要分配选定的 socket.io 本地服务器实例属性,你可以使用 @WebSocketServer() 装饰器来简单地对属性进行装饰。

import { WebSocketGateway, WebSocketServer, SubscribeMessage } from '@nestjs/websockets';

@WebSocketGateway({ port: 81, namespace: 'users' })
export class UsersGateway {
    @WebSocketServer() 
    private server: object;

    @SubscribeMessage('drop')
    handleDropMessage(sender, data) {
        // sender is a native socket.io client object
    }
}

Value will be assigned after server initialization.

服务器初始化完成后将分配值。

依赖注入

Gateway is a Component, so it can inject dependencies through constructor. Gateway also can be injected into another component.

网关是一个组件,所以可以通过构造函数注入依赖。网关也可以被注入到另一个组件中。