> For the complete documentation index, see [llms.txt](https://www.socketio4j.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.socketio4j.org/server-api/server-api-4.0-zh/ru-men-zhi-nan/server-instance.md).

# 服务器实例

## 创建服务器

要启动 Socket.IO 服务器，请创建一个 `配置`，设置绑定地址和端口，然后启动服务器。

```java
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(9092);

SocketIOServer server = new SocketIOServer(config);
```

{% hint style="warning" %}
使用诸如此类框架时 **Spring Boot**，确保你导入 `com.socketio4j.socketio.Configuration` 而不是具有相同名称的框架类（例如， `org.springframework.context.annotation.Configuration`），以避免导入冲突。
{% endhint %}

## 启动服务器

{% tabs %}
{% tab title="同步" %}

```java
server.start()
```

{% endtab %}

{% tab title="异步" %}

```java
server.startAsync().addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("Server started on " + config.getPort());
            } else {
                System.out.println("Error " + future.cause().getLocalizedMessage());
            }
        });
```

{% endtab %}
{% endtabs %}

## 停止服务器

在关闭期间始终优雅地停止服务器。

```java
server.stop();
```

{% hint style="info" %}
socketio4j 在服务器启动后添加了关闭钩子，它会在某些场景下优雅地停止服务器，但并非所有情况。始终建议显式停止服务器。
{% endhint %}

## 完整示例

{% code title="Server.java" %}

```java
import com.socketio4j.socketio.Configuration;
import com.socketio4j.socketio.SocketIOServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SocketIoServerMain {
    
    private static final Logger log = LoggerFactory.getLogger(SocketIoServerMain.class);
    
    public static void main(String[] args) throws Exception {
        // 创建配置
        Configuration config = new Configuration();
        config.setHostname("localhost");
        config.setPort(9092);

        // 创建服务器
        SocketIOServer server = new SocketIOServer(config);
        
        server.addConnectListener(client -> {
            log.info("[/] connected -> " + client.getSessionId());
        });
        server.addDisconnectListener(client -> {
            log.info("[/] disconnected -> " + client.getSessionId());
        });
        
        server.addEventListener("hi", String.class, (client, data, ack) -> {
            // 在客户端监听 "reply"
            log.info("received data : " + data);
            client.sendEvent("reply", "hello");
        });
        // 启动服务器
        server.start();
        log.info("Socket.IO server started on port 9092");

        // 保持 JVM 运行
        Thread.currentThread().join();
    }
}

```

{% endcode %}

{% hint style="info" %}
检查 [事件](https://www.socketio4j.org/events/events-zh/) 有关事件处理的相关文档&#x20;
{% endhint %}

## 注意

* `主机名` 是可选的。如果未设置，服务器将绑定到所有接口（`0.0.0.0` / `::0`).
* `端口` **必须** 在启动服务器之前设置。
* 线程、传输和其他高级选项可以通过 `配置` 在调用之前进行自定义， `start()`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://www.socketio4j.org/server-api/server-api-4.0-zh/ru-men-zhi-nan/server-instance.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
