NestJS websocket向客户端广播事件 [英] NestJS websocket Broadcast event to clients

查看:122
本文介绍了NestJS websocket向客户端广播事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用网络套接字将数据从服务器NestJS发送到客户端.什么都没发出.

I'm not able to send data from server NestJS to clients with a websocket. Nothing is emitted.

我的用例:

  • 几个客户端通过websocket连接到服务器
  • 客户端通过网络套接字向服务器发送消息
  • 服务器将消息广播给所有客户端

我的堆栈:

  • 带有websocket的NestJS服务器
  • Angular客户端和其他客户端(例如用于测试websocket的chrome扩展程序)

我的代码:

simple-web-socket.gateway.ts:

import { SubscribeMessage, WebSocketGateway, WsResponse, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit } from '@nestjs/websockets';

@WebSocketGateway({ port: 9995, transports: ['websocket'] })
export class SimpleWebSocketGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {

  @WebSocketServer() private server: any;
  wsClients=[];
  afterInit() {
    this.server.emit('testing', { do: 'stuff' });
  }

  handleConnection(client: any) {
    this.wsClients.push(client);
  }

  handleDisconnect(client) {
    for (let i = 0; i < this.wsClients.length; i++) {
      if (this.wsClients[i].id === client.id) {
        this.wsClients.splice(i, 1);
        break;
      }
    }
    this.broadcast('disconnect',{});
  }
  private broadcast(event, message: any) {
    const broadCastMessage = JSON.stringify(message);
    for (let c of this.wsClients) {
      c.emit(event, broadCastMessage);
    }
  }

  @SubscribeMessage('my-event')
  onChgEvent(client: any, payload: any) {
    this.broadcast('my-event',payload);
  }
}

main.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from '@nestjs/websockets';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new WsAdapter());
  await app.listen(3000);
}
bootstrap();

app.module.ts:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { SimpleWebSocketGateway } from 'simple-web-socket/simple-web-socket.gateway';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService, SimpleWebSocketGateway],
})
export class AppModule {}

其他信息:

发出(代码行为c.emit(event,broadCastMessage);)的客户端返回false.

Client emiting (with code line c.emit(event, broadCastMessage);) return false.

我怀疑框架中的错误,因为我的用法很简单.但是,如果我做错了什么,我想在这里与社区再次确认.

I suspect an error in framework as my usage is quite simple. But I want to double check with community here if I'm doing something wrong.

谢谢!

推荐答案

如先前的评论中所述,c.send()可以很好地与以下代码配合使用:

As mentionned in previous comment, c.send() works fine with this code:

import { SubscribeMessage, WebSocketGateway, WsResponse, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit } from '@nestjs/websockets';

@WebSocketGateway({ port: 9995, transports: ['websocket'] })
export class SimpleWebSocketGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {

  @WebSocketServer() private server: any;
  wsClients=[];
  afterInit() {
    this.server.emit('testing', { do: 'stuff' });
  }

  handleConnection(client: any) {
    this.wsClients.push(client);
  }

  handleDisconnect(client) {
    for (let i = 0; i < this.wsClients.length; i++) {
      if (this.wsClients[i] === client) {
        this.wsClients.splice(i, 1);
        break;
      }
    }
    this.broadcast('disconnect',{});
  }
  private broadcast(event, message: any) {
    const broadCastMessage = JSON.stringify(message);
    for (let c of this.wsClients) {
      c.send(event, broadCastMessage);
    }
  }

  @SubscribeMessage('my-event')
  onChgEvent(client: any, payload: any) {
    this.broadcast('my-event',payload);
  }
}

这篇关于NestJS websocket向客户端广播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆