# 4.1.16 服务器命名空间(nsp) server\_of\_nsp

* `nsp` (String|RegExp|Function)
* **Returns** `Namespace`

通过路径名标识符`nsp`初始化并检索给定的`namespcae`。如果命名空间已经初始化，它会立即返回它。

```javascript
const adminNamespace= io.of("/admin");
```

还可以提供regex或函数，以便以动态方式创建命名空间：

```javascript
const dynamicNsp =io.of(/^\/dynamic-\d+$/).on('connect',(socket)=>{
    const newNamepsace= socket.nsp;// newNamespace.name==='/dynamic-101'

    // 给所有订阅这个命名空间的客户端广播
    newNamespace.emit('hello')

})

// 客户端

const socket=io('/dynmice-101');

// 广播到每个订阅的命名空间中的所有客户端
dynamicNsp.emit('hello');

// 为每个订阅的命名空间使用中间件

dynamicNsp.use((socket,next)=>{
    //(>^ω^<)
})
```

具体函数：

```javascript
io.of((name,query,next)=>{
    next(null,checkToken(query.token));
}).on('connect',socket=>{
    //your code
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://socket.gitbook.io/docs/4-fu-wu-duan-apiserverapi/4.1-server/server_of_nsp.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
