[英]How to create rooms with nestjs and socket.io
I'm trying to create a room on my nestjs backend but can't find any information on this subject.我正在尝试在我的 nestjs 后端创建一个房间,但找不到有关此主题的任何信息。 You can find the docs here .
您可以在此处找到文档。 The docs don't seem to have anything on this subject.
文档似乎没有关于这个主题的任何内容。
import {
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
WsResponse,
} from '@nestjs/websockets';
import { Client, Server } from 'socket.io';
@WebSocketGateway({namespace: 'story'})
export class StoryEventsGateway {
@WebSocketServer()
server: Server;
@SubscribeMessage('createRoom')
createRoom(client: Client, data: string): WsResponse<unknown> {
return { event: 'roomCreated', data };
}
}
By changing client: Client
to socket: Socket
you're able to use the socket object you are used to when using socket.io .通过将
client: Client
更改为socket: Socket
您可以使用在使用socket.io时习惯使用的 socket 对象。
Here is the edited function.这是编辑后的功能。
import { Socket } from 'socket.io';
import { WsResponse } from '@nestjs/websockets';
createRoom(socket: Socket, data: string): WsResponse<unknown> {
socket.join('aRoom');
socket.to('aRoom').emit('roomCreated', {room: 'aRoom'});
return { event: 'roomCreated', room: 'aRoom' };
}
With the latest Nest JS update you can use this code where the room name can be sent from the front-end and it will passed on to the 'data' variable:使用最新的 Nest JS 更新,您可以使用此代码,其中可以从前端发送房间名称,并将其传递给“数据”变量:
@SubscribeMessage('createRoom')
createRoom(@MessageBody() data: string, @ConnectedSocket() client: Socket) {
client.join(data, err => {
if (err) {
this.logger.error(err);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.