admin管理员组

文章数量:1321056

I'm encountering the following error in my NestJS WebSocket Gateway implementation:

TypeError: this.server.of is not a function

I am using @nestjs/websockets with socket.io, and when trying to use this.server.of('/users') to emit messages to a specific namespace, I get the error. Here's the relevant code:

@WebSocketGateway(3002, {
  namespace: '/chat',
})
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  constructor(
    private readonly connectionsService: ConnectionsService,
    private readonly usersService: UsersService,
  ) {}

  async handleConnection(client: Socket) {
    // Create a new user for the connection
    await this.usersService.create({
      userId: '1234',
      name: 'Alice',
      userCode: 'XY56AB',
    });

    console.log('Client connected', client.id);
  }

  handleDisconnect(client: Socket) {
    console.log('Client disconnected', client.id);
  }

  @SubscribeMessage('chat:message')
  async handleMessage(client: Socket, payload: any) {
    try {
      // Send new updated connection to the client
      const allConnections = await this.connectionsService.findAll(
        '1234',
      );

      // Trying to emit to the '/users' namespace (this is where the error occurs)
      this.server
        .of('/users')  // This line throws the error
        .to('5678')  // The target socket ID
        .emit('chat:responseAll', allConnections);
    } catch (error) {
      console.error('-----', error);
    }
  }
}

When calling this.server.of('/users'), I get the error TypeError: this.server.of is not a function. I tried searching for any relevant changes in the API for Socket.IO or @nestjs/websockets, but couldn't find a solution.

Can someone help me resolve this issue or explain why this.server.of() is not working in my case?


Note: The idea is next, i need to send a message from one namespace to another.

I'm encountering the following error in my NestJS WebSocket Gateway implementation:

TypeError: this.server.of is not a function

I am using @nestjs/websockets with socket.io, and when trying to use this.server.of('/users') to emit messages to a specific namespace, I get the error. Here's the relevant code:

@WebSocketGateway(3002, {
  namespace: '/chat',
})
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  constructor(
    private readonly connectionsService: ConnectionsService,
    private readonly usersService: UsersService,
  ) {}

  async handleConnection(client: Socket) {
    // Create a new user for the connection
    await this.usersService.create({
      userId: '1234',
      name: 'Alice',
      userCode: 'XY56AB',
    });

    console.log('Client connected', client.id);
  }

  handleDisconnect(client: Socket) {
    console.log('Client disconnected', client.id);
  }

  @SubscribeMessage('chat:message')
  async handleMessage(client: Socket, payload: any) {
    try {
      // Send new updated connection to the client
      const allConnections = await this.connectionsService.findAll(
        '1234',
      );

      // Trying to emit to the '/users' namespace (this is where the error occurs)
      this.server
        .of('/users')  // This line throws the error
        .to('5678')  // The target socket ID
        .emit('chat:responseAll', allConnections);
    } catch (error) {
      console.error('-----', error);
    }
  }
}

When calling this.server.of('/users'), I get the error TypeError: this.server.of is not a function. I tried searching for any relevant changes in the API for Socket.IO or @nestjs/websockets, but couldn't find a solution.

Can someone help me resolve this issue or explain why this.server.of() is not working in my case?


Note: The idea is next, i need to send a message from one namespace to another.

Share Improve this question edited Jan 24 at 2:29 shotor 1,06210 silver badges28 bronze badges asked Jan 17 at 20:01 AskingAsking 4,21221 gold badges82 silver badges163 bronze badges 7
  • Make sure you are importing the Server Object from the socket.io. – Abdul Mattee Commented Jan 20 at 7:17
  • @AbdulMattee, i use import { Server, Socket } from 'socket.io'; – Asking Commented Jan 20 at 8:56
  • I tried the same of and to methods and it worked on my side, to debug the issue on your side I would recommend to use the Copilot or Cursor IDE, they can get the context of the code and debug the issues better. – Abdul Mattee Commented Jan 20 at 11:36
  • @AbdulMattee did you use nest js and sockets packages? – Asking Commented Jan 20 at 20:09
  • @AbdulMattee, i have this deps: "@nestjs/platform-socket.io": "^11.0.1", "@nestjs/websockets": "^11.0.1", – Asking Commented Jan 20 at 20:40
 |  Show 2 more comments

1 Answer 1

Reset to default 0

Explanation
In a typical NestJS WebSocket Gateway, this.server refers to the Server instance created by the WebSocket gateway. Depending on your setup, it might not have the methods you expect, such as to.

If you need to use the to method (or other methods on the server), ensure you're accessing it correctly. In some setups, you may need to drill down further to get the actual Socket.IO server instance.

Solution Instead of calling this.server.to(...), you may need to use this.server.server.to(...). Here's an example:

Incorrect: this.server.to('room').emit('event', payload);

Correct: this.server.server.to('room').emit('event', payload);

For some reason, the TypeScript types indicate that the incorrect version (this.server.to(...)) should be used. However, the correct implementation requires calling this.server.server.to(...). To resolve this mismatch, I had to suppress the TypeScript error.

本文标签: TypeError thisserverof is not a function in NestJS WebSocket Gateway with SocketIOStack Overflow