---
title: 从房间中移除特定用户
slug: world-sdk-guide-ch/oGIMmJKkyxnwqVRFfc3b9
docTags: 
createdAt: 2024-09-02T08:34:13.135Z
---

您可以在运行时将某些用户踢出房间。

:::hint{type="danger"}
- 请创建服务器代码 index.ts Sandbox。
:::

## 函数定义

| kick(client: SandboxPlayer, reason?: string): Promise; | 这是一个在接收到带有 SessionID 的 SandboxPlayer 后将其踢出的函数。<br /><br />- 如果您被踢出，将会出现一个弹出窗口，通知您已被踢出，但该弹出窗口是 ZEPETO 应用的 UI，编辑器无法检查。 |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |

:::hint{type="info"}
**📘&#x20;**&#x8BF7;参考以下指南。 \[[ZEPETO.Multiplay(Server) API](https://developer.zepeto.me/docs/multiplay-server/classes/ZEPETO_Multiplay.Sandbox#kick)]
:::



首先，要获取用户信息，请定义 Schema Types 和 RoomState，如下所示：

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-oVK3n8knNlRPitGOhHD1y-20240904-102428.png)

## 使用示例

- 使用 UserInfos 中的数据获取将被踢出的用户的 session ID。
- 导入带有 session ID 的沙盒播放器后，调用踢出功能。
- 我可以通过广播告诉你谁被踢出了。

```typescript
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}`);
    }
}
```

:::hint{type="success"}
**👍 默认情况下，被踢出的用户可以再次进入房间**

- 为了防止这种情况，使用基于 UserId 的 DataStorage 管理功能来存储被用户踢出的房间信息。
- 您可以在尝试进入房间时调用踢出功能来实现。
:::

