Nest: Question about WebSocketGateway class - Emit to channel from external component

Created on 15 Aug 2017  路  5Comments  路  Source: nestjs/nest

Hi,

I have a simple WebSocketGateway:

import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';

@WebSocketGateway({ port: 3001, namespace: 'ws' })
export class TestGateway {
  @SubscribeMessage('channel-1')
  onMessage(client, data) {
    client.emit('channel-1', data);
  }
}

I'm trying to send messages (broadcast) to this channel from other parts of the application (others components that can be or not inside the same module).

There is a way to do it without connecting via a socket.io client?

Thanks

Most helpful comment

Any idea to emit from controller?

All 5 comments

Solved it using:

  @WebSocketServer() 
  private server: any;

So I can:

this.server.emit('channel-1', 'Hey!');

Any idea to emit from controller?

Any idea to emit from controller?

Any idea to emit from controller?

in controller you will call the function on the gateway example:

@MessagePattern({ cmd: 'broadcast_all' })
async broadcastAll(data: exampleDTO) {
return await this.exampleGateway.brodcastAll(data);
}

and in gateway:
@WebSocketServer() server;
async brodcastAll(data) {
try {
this.server.emit('example_event', data);
} catch (e) {
//handle error here
}
}

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cojack picture cojack  路  3Comments

cdiaz picture cdiaz  路  3Comments

breitsmiley picture breitsmiley  路  3Comments

marshall007 picture marshall007  路  3Comments

menme95 picture menme95  路  3Comments