Docs:
λ yarn add @nestjs/websockets
λ nest g ga events
events.gateway.js
import { SubscribeMessage, WebSocketGateway, WsResponse, WebSocketServer } from '@nestjs/websockets';import { Observable, of } from 'rxjs';import { map } from 'rxjs/operators'const l = console.log@WebSocketGateway()export class EventsGateway { @WebSocketServer() server; @SubscribeMessage('events') onEvent(client: any, payload: any): Observable> | any { // this.server.emit('resmsg', data); // io.emit('resmsg', payload) let { name } = payload; if (name === 'ajanuw') { return of({ event: 'events', data: { msg: 'hello ajanuw!' } }) } if (name === 'alone') { return of('hi', '实打实') .pipe( map($_ => ({ event: 'events', data: { msg: $_ } })) ); } return of(payload); }}
app.module.ts
import { EventsGateway } from './events/events.gateway'@Module({ providers: [EventsGateway],})
客户端
监听进入与离开
import { SubscribeMessage, WebSocketGateway, WsResponse, WebSocketServer,} from '@nestjs/websockets';import { Observable, of } from 'rxjs';const l = console.log;let num = 0;@WebSocketGateway()export class EventsGateway { @SubscribeMessage('message') onEvent(client: any, payload: any): Observable> { num++ console.log(`有一位用户链接!> ${num}`); client.on('disconnect', () => { num-- console.log(`有人离开了...> ${num}`); }) return of({ event: 'message', data: '233' }); }}