Nest.js WebSocket

Posted Ajanuw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nest.js WebSocket相关的知识,希望对你有一定的参考价值。

Docs: https://docs.nestjs.com/websockets/gateways

λ 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<WsResponse<any>> | any {
    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],
})

客户端

  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
  <script>
    const l = console.log
    let socket = io('http://localhost:5000');
    socket.on('connect', function () {
      console.log('链接成功');

      // 发射
      socket.emit('events', {
        name: 'ajanuw'
      });

      // 发射
      socket.emit('events', {
        name: 'alone'
      });

      // 发射
      // socket.emit('identity', 0, (response) => console.log('Identity:', response));
    });
    
    // 监听
    socket.on('events', (data) => {
      l(data.msg)
    });
  </script>

以上是关于Nest.js WebSocket的主要内容,如果未能解决你的问题,请参考以下文章

前端工程师梭哈初体验(基于Nest.js写服务端代码)

Nest.Js 不接受任何更改

在 nest.js 代码库上找不到模块 (MODULE_NOT_FOUND)

Nest.js:如何覆盖导入模块中的提供程序?

请求正文未显示在 Nest.js + Swagger 中

如何在单元测试 Nest.js 中测试抛出新的 HttpException