> 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-es/comenzando/server-instance.md).

# Instancia del servidor

## Creando un servidor

Para iniciar un servidor Socket.IO, crea un `Configuración`, establece la dirección de enlace y el puerto, y luego inicia el servidor.

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

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

{% hint style="warning" %}
Al usar frameworks como **Spring Boot**, asegúrate de importar `com.socketio4j.socketio.Configuration` y no clases del framework con el mismo nombre (por ejemplo, `org.springframework.context.annotation.Configuration`), para evitar conflictos de importación.
{% endhint %}

## Iniciando el servidor

{% tabs %}
{% tab title="Sincrónico" %}

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

{% endtab %}

{% tab title="Asincrónico" %}

```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 %}

## Deteniendo el servidor

Siempre detén el servidor de forma ordenada durante el apagado.

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

{% hint style="info" %}
socketio4j agrega un hook de apagado después de que el servidor se inicia; detiene el servidor de forma ordenada en ciertos escenarios, no en todos. Siempre se recomienda detener el servidor explícitamente.
{% endhint %}

## Ejemplo completo

{% 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 {
        // Crear configuración
        Configuration config = new Configuration();
        config.setHostname("localhost");
        config.setPort(9092);

        // Crear servidor
        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) -> {
            //escuchar "reply" en el cliente
            log.info("received data : " + data);
            client.sendEvent("reply", "hello");
        });
        // Iniciar servidor
        server.start();
        log.info("Socket.IO server started on port 9092");

        // Mantener la JVM viva
        Thread.currentThread().join();
    }
}

```

{% endcode %}

{% hint style="info" %}
Comprobar [Eventos](https://www.socketio4j.org/events/events-es/) para la documentación relacionada con el manejo de eventos&#x20;
{% endhint %}

## Notas

* `hostname` es opcional. Si no se establece, el servidor se enlaza a todas las interfaces (`0.0.0.0` / `::0`).
* `puerto` **debe** establecerse antes de iniciar el servidor.
* El subproceso, los transportes y otras opciones avanzadas pueden personalizarse mediante `Configuración` antes de llamar a `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-es/comenzando/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.
