NestJS websocket向客户端广播事件

时间:2018-12-04 09:35:59

标签: websocket nestjs

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

我的用例:

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

我的堆栈:

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

我的代码:

simple-web-socket.gateway.ts:

func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith
     payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void)

main.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);
  }
}

app.module.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();

其他信息:

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

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

谢谢!

3 个答案:

答案 0 :(得分:1)

如之前的评论中所述,c.send()可以在以下代码中正常工作:

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);
  }
}

答案 1 :(得分:1)

通过 socket.io,我们可以使用 socket.broadcast.emit()?:

@SubscribeMessage('my-event')
onChgEvent(
    @MessageBody() message: any,
    @ConnectedSocket() socket: Socket,
): void {
   socket.broadcast.emit('my-event', message);
}

答案 2 :(得分:0)

我尝试使用client.send()向所有连接的客户端广播消息:

broadcastMessage(event: string, payload: any) {
  for (const client of this.clients) {
    client.send(event, payload);
  }
}

testBroadcast() {
  this.broadcastMessage('msgInfo', { name: 'foo' });
}

发送的数据最终看起来像这样:

["message", "msgInfo", { "name": "foo" }]

上面的内容对我不起作用,因此我改用了client.emit(),它工作正常:

broadcastMessage(event: string, payload: any) {
  for (const client of this.clients) {
    client.emit(event, payload);
  }
}

现在数据看起来像这样:

["msgInfo", { "name": "foo" }]