typescript - TypeError: server.of nie je funkcia pri používaní namespace socket.io s nestjs
Chcem vysielať udalosti naprieč namespaces v socket.io a dostal som túto chybu typu:
backend | this.chatNamespace = io.of("chat");
backend | ^
backend | TypeError: io.of is not a function
tu je môj pôvodný kód. čo som pokazil?
@WebSocketGateway(3000, {
cors : 'http://localhost',
namespace : 'game',
})
export class GameGateway implements OnGatewayInit, OnGatewayConnection{
@WebSocketServer()
server : Server;
chatNamespace : Namespace;
async afterInit(io : Server) {
this.chatNamespace = io.of("chat");
}
async handleConnection(@ConnectedSocket() client: Socket) {
console.log("hello i'm game user!");
this.chatNamespace.emit("sendMessage", "game", "hihi");
client.emit("gameHello", "hello gamer!");
}
}
Nemám tušenie, prečo som dostal túto chybu, pretože vidím, že trieda Server má metódu "of" a jej návratový typ je Namespace.
Skúsil som tiež zmeniť typy io a chatNamespace na any, ale chybová správa bola rovnaká
--
vyriešené! pre každého, kto narazí na rovnaký problém :
@WebSocketGateway({
namespace: 'game',
pingTimeout: 2000,
pingInterval: 5000,
})
export class GameGateway
implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit
{
@WebSocketServer() //you need this decorator to use namespace!
io : Namespace;
//this.io.server.of('chat') <- now you can access to another namespace 'chat' like this
...
}
alebo môžete písať takto :
//be careful!
//don't state namespace here to use io.of('someNamespace')
@WebSocketGateway()
export class Gateway implements OnGatewayInit, OnGatewayConnection{
@WebSocketServer()
io : Server;
@WebSocketServer()
game : Namespace;
@WebSocketServer()
chat : Namespace;
afterInit(){
this.game = this.io.of("/game");
this.chat = this.io.of("/chat");
}
handleConnection(@ConnectedSocket() client: Socket) {
this.game.emit("sendGameHi");
this.chat.emit("sendChatHi");
}
}