从房间中移除特定用户
4 分
您可以在运行时将某些用户踢出房间。
- 请创建服务器代码 index.ts Sandbox。
函数定义
kick(client: SandboxPlayer, reason?: string): Promise; | 这是一个在接收到带有 SessionID 的 SandboxPlayer 后将其踢出的函数。 - 如果您被踢出,将会出现一个弹出窗口,通知您已被踢出,但该弹出窗口是 ZEPETO 应用的 UI,编辑器无法检查。 |
|---|
📘 请参考以下指南。 [ZEPETO.Multiplay(Server) API]
首先,要获取用户信息,请定义 Schema Types 和 RoomState,如下所示:

使用示例
- 使用 UserInfos 中的数据获取将被踢出的用户的 session ID。
- 导入带有 session ID 的沙盒播放器后,调用踢出功能。
- 我可以通过广播告诉你谁被踢出了。
import { Sandbox, SandboxOptions, SandboxPlayer } from 'ZEPETO.Multiplay';
import { DataStorage, loadDataStorage } from 'ZEPETO.Multiplay.DataStorage';
import { UserInfo } from 'ZEPETO.Multiplay.Schema';
export default class extends Sandbox {
onCreate(options: SandboxOptions) {
this.onMessage("Kick", (client: SandboxPlayer, message: string) => {
this.tryKick(client, message);
});
}
onJoin(client: SandboxPlayer) {
const user = new UserInfo();
user.sessionId = client.sessionId;
user.userId = client.userId;
this.state.UserInfos.set(client.userId, user);
}
async tryKick(client: SandboxPlayer, userId: string) {
let player: SandboxPlayer;
if (userId == null) {
player = client;
} else {
const kickPlayerSessionId: string = this.state.UserInfos.get(userId).sessionId;
player = this.loadPlayer(kickPlayerSessionId);
}
console.log(`尝试踢出 : ${player.userId}`);
await this.kick(player);
this.broadcast("Log", `踢出 : ${player.userId}`);
}
}👍 默认情况下,被踢出的用户可以再次进入房间
- 为了防止这种情况,使用基于 UserId 的 DataStorage 管理功能来存储被用户踢出的房间信息。
- 您可以在尝试进入房间时调用踢出功能来实现。