> ## Documentation Index
> Fetch the complete documentation index at: https://haiprotocol.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Transports

> Transport layer options and configurations for the HAIP SDK

<Note>
  **New protocol version released**: This page may contain outdated information.
</Note>

The HAIP SDK supports multiple transport protocols for different environments and use cases. Each transport implements the same interface but uses different underlying communication mechanisms.

## Transport Types

### WebSocket Transport

The default and most feature-complete transport, supporting real-time bidirectional communication.

**Features:**

* Real-time bidirectional communication
* Binary data support
* Automatic reconnection
* Flow control
* Heartbeat monitoring

**Usage:**

```typescript theme={null}
import { createHAIPClient } from "haip-sdk";

const client = createHAIPClient({
  url: "ws://localhost:8080",
  token: "your-jwt-token",
  transport: "websocket",
});
```

**Configuration Options:**

<ParamField body="url" type="string" required>
  WebSocket server URL (ws\:// or wss\://).
</ParamField>

<ParamField body="token" type="string" required>
  JWT authentication token.
</ParamField>

<ParamField body="options" type="WebSocketTransportOptions">
  Additional WebSocket-specific options.
</ParamField>

```typescript theme={null}
interface WebSocketTransportOptions {
  maxReconnectAttempts?: number;
  reconnectDelay?: number;
  heartbeatInterval?: number;
  binaryType?: "arraybuffer" | "blob";
}
```

### Server-Sent Events (SSE) Transport

Browser-only transport using Server-Sent Events for receiving data and HTTP POST for sending.

**Features:**

* Browser-native support
* Automatic reconnection
* HTTP POST for sending messages
* Event stream parsing

**Usage:**

```typescript theme={null}
import { createHAIPClient } from "haip-sdk";

const client = createHAIPClient({
  url: "http://localhost:8080/sse",
  token: "your-jwt-token",
  transport: "sse",
});
```

**Configuration Options:**

<ParamField body="url" type="string" required>
  SSE endpoint URL (http\:// or https\://).
</ParamField>

<ParamField body="token" type="string" required>
  JWT authentication token.
</ParamField>

<ParamField body="options" type="SSETransportOptions">
  Additional SSE-specific options.
</ParamField>

```typescript theme={null}
interface SSETransportOptions {
  maxReconnectAttempts?: number;
  reconnectDelay?: number;
  withCredentials?: boolean;
  headers?: Record<string, string>;
}
```

**Limitations:**

* Browser environment only
* No binary data support
* Unidirectional for receiving (uses HTTP POST for sending)

### HTTP Streaming Transport

Universal transport using fetch streaming for both sending and receiving.

**Features:**

* Works in Node.js and browsers
* Fetch-based streaming
* Automatic reconnection
* Universal compatibility

**Usage:**

```typescript theme={null}
import { createHAIPClient } from "haip-sdk";

const client = createHAIPClient({
  url: "http://localhost:8080/stream",
  token: "your-jwt-token",
  transport: "http-streaming",
});
```

**Configuration Options:**

<ParamField body="url" type="string" required>
  HTTP streaming endpoint URL.
</ParamField>

<ParamField body="token" type="string" required>
  JWT authentication token.
</ParamField>

<ParamField body="options" type="HTTPStreamingTransportOptions">
  Additional HTTP streaming options.
</ParamField>

```typescript theme={null}
interface HTTPStreamingTransportOptions {
  maxReconnectAttempts?: number;
  reconnectDelay?: number;
  timeout?: number;
  headers?: Record<string, string>;
}
```

## Transport Comparison

| Feature            | WebSocket         | SSE                  | HTTP Streaming    |
| ------------------ | ----------------- | -------------------- | ----------------- |
| **Environment**    | Node.js + Browser | Browser only         | Node.js + Browser |
| **Bidirectional**  | ✅                 | ❌ (POST for sending) | ✅                 |
| **Binary Support** | ✅                 | ❌                    | ✅                 |
| **Real-time**      | ✅                 | ✅                    | ✅                 |
| **Reconnection**   | ✅                 | ✅                    | ✅                 |
| **Flow Control**   | ✅                 | ✅                    | ✅                 |
| **Heartbeat**      | ✅                 | ❌                    | ❌                 |
| **Performance**    | Excellent         | Good                 | Good              |
| **Compatibility**  | High              | Medium               | High              |

## Transport Selection

### Choose WebSocket when:

* You need full bidirectional communication
* Binary data support is required
* Maximum performance is needed
* Both Node.js and browser environments

### Choose SSE when:

* Browser-only application
* Server-sent events are preferred
* Simpler server implementation
* Real-time updates are the primary need

### Choose HTTP Streaming when:

* Universal compatibility is required
* Fetch API is preferred
* Both Node.js and browser support needed
* Simpler deployment (no WebSocket server)

## Transport Configuration

### Global Configuration

```typescript theme={null}
const client = createHAIPClient({
  url: "ws://localhost:8080",
  token: "your-jwt-token",
  transport: "websocket",
  // Global transport options
  maxReconnectAttempts: 5,
  reconnectDelay: 1000,
  heartbeatInterval: 30000,
});
```

### Transport-Specific Configuration

```typescript theme={null}
// WebSocket with custom options
const wsClient = createHAIPClient({
  url: "wss://secure-server.com",
  token: "your-jwt-token",
  transport: "websocket",
  options: {
    maxReconnectAttempts: 10,
    reconnectDelay: 2000,
    heartbeatInterval: 15000,
    binaryType: "arraybuffer",
  },
});

// SSE with custom headers
const sseClient = createHAIPClient({
  url: "https://api.example.com/sse",
  token: "your-jwt-token",
  transport: "sse",
  options: {
    withCredentials: true,
    headers: {
      "X-Custom-Header": "value",
    },
  },
});

// HTTP Streaming with timeout
const httpClient = createHAIPClient({
  url: "https://api.example.com/stream",
  token: "your-jwt-token",
  transport: "http-streaming",
  options: {
    timeout: 30000,
    headers: {
      "User-Agent": "HAIP-Client/1.0",
    },
  },
});
```

## Connection Management

### Automatic Reconnection

All transports support automatic reconnection with exponential backoff:

```typescript theme={null}
const client = createHAIPClient({
  url: "ws://localhost:8080",
  token: "your-jwt-token",
  transport: "websocket",
  maxReconnectAttempts: 5, // Maximum reconnection attempts
  reconnectDelay: 1000, // Initial delay (doubles each attempt)
});
```

### Manual Reconnection

```typescript theme={null}
client.on("disconnect", (reason) => {
  console.log("Disconnected:", reason);

  // Manual reconnection
  setTimeout(async () => {
    try {
      await client.connect();
    } catch (error) {
      console.error("Reconnection failed:", error);
    }
  }, 5000);
});
```

## Transport Events

All transports emit the same events:

```typescript theme={null}
client.on("connect", () => {
  console.log("Transport connected");
});

client.on("disconnect", (reason) => {
  console.log("Transport disconnected:", reason);
});

client.on("error", (error) => {
  console.error("Transport error:", error);
});

client.on("message", (message) => {
  console.log("Message received:", message);
});

client.on("binary", (data) => {
  console.log("Binary data received:", data.byteLength, "bytes");
});
```

## Transport Health Monitoring

### Connection State

```typescript theme={null}
const state = client.getConnectionState();
console.log("Connection state:", {
  connected: state.connected,
  handshakeCompleted: state.handshakeCompleted,
  sessionId: state.sessionId,
  reconnectAttempts: state.reconnectAttempts,
});
```

### Performance Metrics

```typescript theme={null}
const metrics = client.getPerformanceMetrics();
console.log("Transport metrics:", {
  messagesSent: metrics.messagesSent,
  messagesReceived: metrics.messagesReceived,
  bytesSent: metrics.bytesSent,
  bytesReceived: metrics.bytesReceived,
  connectionTime: metrics.connectionTime,
});
```

## Transport Switching

You can switch transports by creating a new client:

```typescript theme={null}
// Start with WebSocket
let client = createHAIPClient({
  url: "ws://localhost:8080",
  token: "your-jwt-token",
  transport: "websocket",
});

// Switch to HTTP streaming if WebSocket fails
client.on("error", async (error) => {
  if (error.message.includes("WebSocket connection failed")) {
    console.log("Switching to HTTP streaming...");

    await client.disconnect();

    client = createHAIPClient({
      url: "http://localhost:8080/stream",
      token: "your-jwt-token",
      transport: "http-streaming",
    });

    await client.connect();
  }
});
```

## Transport Testing

### Testing Different Transports

```typescript theme={null}
async function testTransport(transportType: string) {
  const client = createHAIPClient({
    url:
      transportType === "websocket"
        ? "ws://localhost:8080"
        : "http://localhost:8080/stream",
    token: "test-token",
    transport: transportType as any,
  });

  try {
    await client.connect();
    console.log(`${transportType} transport connected successfully`);

    const runId = await client.startRun("test-run");
    await client.sendTextMessage("USER", "Test message", "test", runId);

    await client.disconnect();
    console.log(`${transportType} transport test completed`);
  } catch (error) {
    console.error(`${transportType} transport test failed:`, error);
  }
}

// Test all transports
await testTransport("websocket");
await testTransport("http-streaming");
// SSE only works in browser
if (typeof window !== "undefined") {
  await testTransport("sse");
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Client API" href="/sdk/client" icon="code">
    Learn about the client interface and methods.
  </Card>

  <Card title="Examples" href="/examples/basic-chat" icon="book-open">
    See practical examples of transport usage.
  </Card>

  <Card title="Authentication" href="/sdk/authentication" icon="key">
    Understand authentication across different transports.
  </Card>

  <Card title="API Reference" href="/sdk/api-reference" icon="laptop">
    Full API reference documentation.
  </Card>
</CardGroup>

{" "}
