任务:
我正在尝试获取用户离开聊天室的 HTTP 请求。此信息应该在此聊天中与其他人共享。更准确地说,一步一步:
问题:
我找不到有关 Nest.Controller 和 Nest.Gateways(ws) 之间数据交换的信息。
先决条件:
现在我只通过 Websocket 事件来做到这一点。但在这种情况下,用户界面无法知道用户离开房间的确切时间。 (可以通过 Promise 等待 HTTP 请求,而 websocket 事件则不能)。
非常感谢您的回答。
因此,您正在尝试创建一种流畅的体验,当用户单击“离开房间”按钮时,后端会立即知道,同时房间中的其他人都会收到此人留下的备忘录。棘手的部分是在 HTTP 请求和 WebSocket 事件之间实现sync,对吧?让我们深入探讨如何使用 NestJS 来实现这一目标。
当用户点击“离开房间”时,前端会向服务器发送一个 HTTP 请求,以发出信号:“嘿,该用户想要出去!”这是所有leave room逻辑都位于HTTP Controller中的地方。一旦该请求到达后端,您就可以处理它。
以下是它在控制器中的外观:
@Controller('chat')
export class ChatController {
constructor(private readonly chatService: ChatService) {}
@Post('leave-room')
async leaveRoom(@Body() leaveRoomDto: LeaveRoomDto) {
const { userId, roomName } = leaveRoomDto;
// Handle the user leaving the room in the service
await this.chatService.leaveRoom(userId, roomName);
// Tell the WebSocket Gateway that someone has left the room
this.chatService.notifyRoomLeave(userId, roomName);
// Finally, respond back to the user who left the room
return { message: `You have left room ${roomName}` };
}
}
事情是这样的:
leaveRoom
逻辑,以便UI知道确切何时用户已成功离开房间。这样,HTTP 响应就会告诉用户:“是的,你已经出局了。”现在,在服务中,您不仅处理将用户移出房间的逻辑,还通知 WebSocket Gateway。该服务本质上就像中间人一样 - 一旦用户被删除,它就会触发 WebSocket 告诉房间里的其他人有关更改的信息。
这是正在运行的服务:
@Injectable()
export class ChatService {
constructor(private readonly chatGateway: ChatGateway) {}
async leaveRoom(userId: string, roomName: string) {
// Logic to remove the user from the room (e.g., update DB, remove from room data)
}
notifyRoomLeave(userId: string, roomName: string) {
// Inform the WebSocket Gateway that the user has left
this.chatGateway.userLeftRoom(userId, roomName);
}
}
notifyRoomLeave
WebSocket Gateway,该网关将事件广播给该房间中的所有客户端。
发挥它的魔力了。一旦服务告诉它“嘿,这个用户离开了”,网关就会向房间里的其他人发送一条消息。 以下是在 WebSocket 网关中处理该问题的方法:
@WebSocketGateway()
export class ChatGateway {
@WebSocketServer() server;
userLeftRoom(userId: string, roomName: string) {
// Broadcast the 'user-leave-a-room' event to everyone in the room
this.server.to(roomName).emit('user-leave-a-room', { userId, roomName });
}
}
user-leave-a-room
等待
user-leave-a-room
socket.on('user-leave-a-room', ({ userId, roomName }) => {
console.log(`${userId} left room ${roomName}`);
// Update the chat UI accordingly, maybe show a notification
});