nest icon indicating copy to clipboard operation
nest copied to clipboard

Question about WebSocketGateway class - Emit to channel from external component

Open jgordor opened this issue 9 years ago • 5 comments

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

jgordor avatar Aug 15 '17 11:08 jgordor

Solved it using:

  @WebSocketServer() 
  private server: any;

So I can:

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

jgordor avatar Aug 16 '17 08:08 jgordor

Any idea to emit from controller?

ahmadarif avatar Jan 17 '19 10:01 ahmadarif

Any idea to emit from controller?

Mangdar avatar Jun 01 '19 19:06 Mangdar

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

FilipeMazzon avatar Aug 28 '19 23:08 FilipeMazzon

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.

lock[bot] avatar Nov 26 '19 23:11 lock[bot]