简体   繁体   中英

Socket.io broadcast to room not working

In a node.js application using "socket.io": "^2.0.4"

Socket.io is initialized like this :

export let io: any;

 io = socketio(server,
    {
      secure: secure,
      rejectUnauthorized: false,
    },
  );

  io.set('origins', '*:*');
  io.origins('*:*');

  io.on('connection', (socket) => {
  socket.on('message', async (data) => {
    }
  }

I want to broadcast message to all socket in a room

So I did :

io.to(roomName).emit('message', data);

I logged after io().to().emit() with no issue the roomName and data are ok

But no event pass in message , what am I missing ?

Is your sockect.IO configured properly on the server side, Here is a Low level socket service api based on rxjs for Angular that works and you can use

import { Injectable } from '@angular/core';
import * as socketio from 'socket.io-client';
import {environment} from '../../../environments/environment';
import {Observable} from 'rxjs/Observable';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class SocketService {

  private socket: SocketIOClient.Socket;
  connected$ = new BehaviorSubject<boolean>(false);

  constructor() {
    this.socket = socketio(environment.socket.baseUrl, environment.socket.config);
    this.socket.on('connect', () => this.connected$.next(true));
    this.socket.on('disconnect', () => this.connected$.next(false));
  }

  join(room: string) {
    // auto rejoin after reconnect mechanism
    this.connected$.subscribe(connected => {
      if (connected) {
        this.socket.emit('join', {room});
      }
    });
  }

  disconnect() {
    this.socket.disconnect();
    this.connected$.next(false);
  }

  emit(event: string, data?: any) {

    console.group();
      console.log('----- SOCKET OUTBAND -----');
      console.log('Action: ', event);
      console.log('Payload: ', data);
    console.groupEnd();

    this.socket.emit(event, data);
  }

  listen(event: string): Observable<any> {
    return new Observable( observer => {

      this.socket.on(event, data => {

        console.group();
          console.log('----- SOCKET INBOUND -----');
          console.log('Action: ', event);
          console.log('Payload: ', data);
        console.groupEnd();

        observer.next(data);
      });
      // dispose of the event listener when unsubscribed
      return () => this.socket.off(event);
    });
  }

}

This code is from Avatsaev all thanks to him for sharing his cool app using socket Io with NGRX, you can see how its used with his service code

Try the code below:

socket.broadcast.to(roomName).emit('message', data);

More information: https://socket.io/docs/emit-cheatsheet/#

For anyone who is having a similar issue, make sure that you are emitting the message to the correct namespace. In my case, I needed to emit to the "chat" namespace where all the clients were listening, but just to a specific room.

For instance:

// We still need to specify the namespace, in my case, the "chat" namespace. This is where my clients are listening.
socket.on("special-message", (message) => {
  console.log("Special message is: ", message);
  socket.to("special").emit("chat", message); // Emit to "special" channel inside the "chat" namespace.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM