> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/contributor/contributor-es/comunicaciones/transports.md).

# Transportes

Un *transporte* es una interfaz del lado del cliente que puede conectarse a un URI de comms e intercambiar mensajes en tiempo real con peers o servicios.

{% hint style="info" %}
Puedes ver el protocolo de comms en acción y experimentarlo usando el código abierto [Comms Station](https://decentraland.github.io/comms-station/).
{% endhint %}

Los clientes son libres de implementar transportes como les parezca (siempre que sigan el protocolo esperado por otros clientes y servicios), pero el [diseño recomendado](#recommended) descrito a continuación se ha probado en la práctica y ha demostrado integrarse bien con diferentes proyectos.\`

### Transportes estándar <a href="#types" id="types"></a>

Hay 5 tipos de transporte definidos por el protocolo:

* [WebSocket](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/websocket/README.md) (`ws-room`) utiliza un flujo estándar de WebSocket.
* [LiveKit](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/livekit/README.md) (`livekit`) utiliza el framework de código abierto LiveKit, basado en WebRTC.
* [SignedLogin](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/signed_login/README.md) (`signed-login`) realiza una solicitud HTTPS firmada para obtener un transporte asignado dinámicamente desde un servidor.
* [Offline](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/offline/README.md) (`offline`) es un transporte ficticio que indica que no hay comms en el entorno actual.
* [Simulator](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/simulator/README.md) (`simulator`) es un transporte ficticio con un comportamiento completamente personalizado, principalmente para que los desarrolladores depuren sus implementaciones.

Los mensajes enviados y recibidos a través de una interfaz de transport siempre son iguales (véase [mensajes](https://github.com/decentraland/docs/tree/main/contributor/communications/messages/README.md)). Algunos transportes pueden envolverlos en estructuras de control para su transmisión, pero estas deben desempaquetarse antes de cruzar la `Transport` interfaz.

### Diseño recomendado <a href="#recommended" id="recommended"></a>

Este es un `Transport` interfaz escrita en TypeScript:

```ts
interface Transport {
  // Inicializa el Transport con un URI:
  constructor(private uriWithConnectionParams: string)

  // Abre una conexión usando el URI dado en el constructor:
  connect(): Promise<void>

  // Cierra la conexión:
  disconnect(): Promise<void>

  // Envía una carga útil arbitraria al servicio y a todos los peers:
  send(packet: Packet): Promise<void>

  // Suscríbete a los mensajes entrantes tanto del servicio como de todos los peers:
  on(event: 'receive', callback: (packet: Packet) => void): void
}
```

Las implementaciones reales suelen extender esto, añadiendo eventos de conexión/desconexión y entrada/salida, envío sin difusión, tipado más estricto o adaptaciones específicas del lenguaje.

#### URI de transporte

Los valores de `uriWithConnectionParams` siempre tienen la forma:

```
<type>:<type connection parameters>
```

El `<type>` corresponde a uno de los enumerados arriba, y el formato de `<type connection parameters>` depende del transporte específico. Puede ser una URL, un token opaco o cualquier dato arbitrario.

El [LiveKit](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/livekit/README.md) transporte, por ejemplo, usa una `wss` URL con un `access_token` parámetro para establecer una conexión autenticada:

```
livekit:wss://comms.example.com?access_token=eyJhbGciOiJI...
```

A modo de comparación, el [WebSocket](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/websocket/README.md) transporte también usa una `wss` URL, pero sin un token pre-generado. Requiere un flujo de autenticación una vez conectado.

#### Creando transportes

Dado que cada `Transport` clase admitirá un tipo particular de URI, es una buena idea tener un método de fábrica que devuelva un `Transport` o falle de inmediato. Por ejemplo:

```ts
function createTransport(uriWithConnectionParams: string) {
  const type = getPrefix(urlWithConnectionParams)

  switch (type) {
    case 'ws-room': return new WsRoomTransport(uriWithConnectionParams)
    case 'livekit': return new LiveKitTransport(uriWithConnectionParams)
    // ... otras implementaciones compatibles...
  }

  throw new Error(`Tipo de transporte no compatible: ${type}`)
}
```

No se requiere que los clientes implementen todos los transportes estándar. Si pretenden usar solo un subconjunto de los tipos definidos sin intentar manejar todas las URIs, son libres de rechazar los tipos que no admitan.

Se aconseja a los clientes más completos, como un World Explorer, que implementen al menos los [WebSocket](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/websocket/README.md) y [LiveKit](https://github.com/decentraland/docs/tree/main/contributor/communications/transport-types/livekit/README.md) transports, que actualmente están en uso por todos los realms principales.

### Más información

Ve a una [sección específica del tipo de transporte](#types) lee sobre los diferentes [tipos de mensajes](https://github.com/decentraland/docs/tree/main/contributor/communications/messages/README.md) o consulta la \[\[Comms Demo Station]].


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/contributor/contributor-es/comunicaciones/transports.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
