zoukankan      html  css  js  c++  java
  • 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 {
        // 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],
    })
    

    客户端

      <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>
    

    监听进入与离开

    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<WsResponse<any>> {
        num++
        console.log(`有一位用户链接!> ${num}`);
        client.on('disconnect', () => {
          num--
          console.log(`有人离开了...> ${num}`);
        })
        return of({ event: 'message', data: '233' });
      }
    }
    
  • 相关阅读:
    .Net 框架培训
    根据 XSD生成 Data Contract之怪现象
    WCF performance
    IIS7 performance
    【原】[SQL function] SQL Server Split Function
    【原】[Data.Common.Format] 格式化传入的float(浮点型)字符串
    【原】[Crystal Reports] 当前一条记录与前一条记录比较
    【转】C#中处理XML文档的方法
    【原】Crystal Reports水晶报表 格式化传入的float字符串
    【转】[ASP] 用 ASP 创建 GUID
  • 原文地址:https://www.cnblogs.com/ajanuw/p/9734517.html
Copyright © 2011-2022 走看看