typescriptwebsocketsocket.ionestjs

How to add different namespace clients to the same room?


I created two socket.io namespaces because there is an agent and customer in chat application and their handleConnection, handleDisconnect functions and etc. are different. That is why I separated them instead of writing if-else blocks to differentiate who connects. So now the issue occurs: I can not add them to the same room, because room is bounded to the namespace which is created in. Is there any way to do so? Or separating them is not even correct? I tried to implement this and this to test, but they did not work either even there is of function in Server class.

TypeError: this.server.of is not a function at CustomerGateway.handleConnection 
@WebSocketGateway({ cors: { origin: '*' }, namespace: '/customer' })
export class CustomerGateway implements OnGatewayConnection, OnGatewayDisconnect {
  constructor(private readonly chatService: ChatService) {}

  @WebSocketServer() server: Server;

  async handleConnection(client: Socket) {
    console.log(`Connected customer: ${client.id}`);
    console.log(this.server.of('/customer'));
    const key = '';
    const room = `room:${key}`;
    client.join(room);
  }

Solution

  • I implemented this solution to solve the issue. As mentioned in the question, rooms are scoped to their respective namespaces. However, creating rooms with the same name in both namespaces solves the problem. While clients from different namespaces are still not in the same room, this approach allows the customer to know which room the agent is in within their own namespace, enabling the customer to send messages accordingly.

    For example, in the AgentGateway class (which handles events for the agent namespace), the chatMessage.room exists in both namespaces. The agent can send a message using this.io.server.of('/customer')....

    @WebSocketGateway({ cors: { origin: '*' }, namespace: '/customer' })
    export class CustomerGateway implements OnGatewayConnection, OnGatewayDisconnect {
    
      @WebSocketServer() 
      server: Server;
    
      @WebSocketServer()
      io: Namespace;
    
      @SubscribeMessage('sendMessage')
      async handleSendMessage(@MessageBody() chatMessage: ChatMessage, @ConnectedSocket() client: Socket) {
        client.emit('sendMessage', chatMessage);
        return this.io.server.of('/agent').to(chatMessage.room).emit('sendMessage', chatMessage);
      }
    }
    

    about the TypeError error: of function should not be called on server variable, instead io variable should be created with the Namespace type and @WebSocketServer() decarotor