1. 程式人生 > >Nest.js WebSocket

Nest.js WebSocket

events sre ESS ons ket data 客戶端 per soc

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