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

# WebSocket Transports

> WebSocket transport implementations for real-time client-server communication

## Overview

WebSocket transports provide both client and server WebSocket implementations for real-time bidirectional communication. These transports support audio streaming, frame serialization, and connection management, making them ideal for prototyping and lightweight client-server applications where WebRTC might be overkill.

<Warning>
  WebSocket transports are best suited for prototyping and controlled network environments.

  For production client-server applications, we recommend WebRTC-based transports for more robust network handling, NAT traversal, and media optimization.
</Warning>

<CardGroup cols={2}>
  <Card title="WebSocket Client API Reference" icon="code" href="https://reference-server.pipecat.ai/en/latest/api/pipecat.transports.websocket.client.html">
    Client transport methods and configuration
  </Card>

  <Card title="WebSocket Server API Reference" icon="code" href="https://reference-server.pipecat.ai/en/latest/api/pipecat.transports.websocket.server.html">
    Server transport methods and configuration
  </Card>

  <Card title="Example Implementation" icon="play" href="https://github.com/pipecat-ai/pipecat-examples/tree/main/websocket">
    Complete client and server WebSocket examples
  </Card>

  <Card title="WebSocket Protocol" icon="book" href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">
    WebSocket protocol documentation and guides
  </Card>
</CardGroup>

## Installation

To use WebSocket transports, install the required dependencies:

```bash theme={null}
uv add "pipecat-ai[websocket]"
```

## Prerequisites

### WebSocket Application Setup

Before using WebSocket transports, you need:

1. **Server Implementation**: Set up WebSocket server using your preferred framework
2. **Client Implementation**: Configure WebSocket client for browser or application use
3. **Audio Configuration**: Set up audio streaming parameters and formats
4. **Connection Management**: Handle WebSocket lifecycle and error recovery

### Configuration Options

* **Transport Type**: Choose between client or server WebSocket transport
* **Audio Parameters**: Configure sample rates, channels, and audio formats
* **Frame Serialization**: Set up custom frame serializers if needed
* **Connection Handling**: Configure reconnection and error handling strategies

### Key Features

* **Bidirectional Communication**: Real-time audio and data streaming
* **Simple Protocol**: Lightweight WebSocket-based communication
* **Flexible Serialization**: Support for custom frame formats and audio codecs
* **Cross-Platform**: Works with any WebSocket-compatible client or server

## Configuration

### WebsocketServerTransport

<ParamField path="params" type="WebsocketServerParams" required>
  Transport configuration parameters.
</ParamField>

<ParamField path="host" type="str" default="localhost">
  Host address to bind the WebSocket server to.
</ParamField>

<ParamField path="port" type="int" default="8765">
  Port number to bind the WebSocket server to.
</ParamField>

<ParamField path="input_name" type="str" default="None">
  Optional name for the input transport processor.
</ParamField>

<ParamField path="output_name" type="str" default="None">
  Optional name for the output transport processor.
</ParamField>

### WebsocketServerParams

Inherits from `TransportParams` with additional WebSocket-specific parameters.

<ParamField path="add_wav_header" type="bool" default="False">
  Whether to add WAV headers to outgoing audio frames.
</ParamField>

<ParamField path="serializer" type="FrameSerializer" default="None">
  Frame serializer for encoding/decoding WebSocket messages.
</ParamField>

<ParamField path="session_timeout" type="int" default="None">
  Timeout in seconds for client sessions. When set, triggers
  `on_session_timeout` if the session exceeds this duration. `None` disables the
  timeout.
</ParamField>

### WebsocketClientTransport

<ParamField path="uri" type="str" required>
  The WebSocket URI to connect to.
</ParamField>

<ParamField path="params" type="WebsocketClientParams" default="WebsocketClientParams()">
  Client transport configuration parameters.
</ParamField>

<ParamField path="input_name" type="str" default="None">
  Optional name for the input transport processor.
</ParamField>

<ParamField path="output_name" type="str" default="None">
  Optional name for the output transport processor.
</ParamField>

### WebsocketClientParams

Inherits from `TransportParams` with additional WebSocket-specific parameters.

<ParamField path="add_wav_header" type="bool" default="True">
  Whether to add WAV headers to outgoing audio frames.
</ParamField>

<ParamField path="additional_headers" type="dict[str, str]" default="None">
  Optional additional HTTP headers to include in the WebSocket handshake.
</ParamField>

<ParamField path="serializer" type="FrameSerializer" default="None">
  Frame serializer for encoding/decoding WebSocket messages.
</ParamField>

## Usage

WebSocket transports provide simple client-server communication for audio streaming and real-time interaction. They are ideal for prototyping and controlled network environments.

See the [complete examples](https://github.com/pipecat-ai/pipecat-examples/tree/main/websocket) for full implementations including:

* WebSocket server setup and configuration
* Client-side WebSocket integration
* Audio streaming and frame handling
* Connection management and error recovery

## Event Handlers

WebSocket transports provide event handlers for client connection lifecycle and session management. Register handlers using the `@event_handler` decorator on the transport instance.

### WebsocketServerTransport Events

#### Events Summary

| Event                    | Description                                     |
| ------------------------ | ----------------------------------------------- |
| `on_client_connected`    | Client WebSocket connected                      |
| `on_client_disconnected` | Client WebSocket disconnected                   |
| `on_session_timeout`     | Session timed out                               |
| `on_websocket_ready`     | WebSocket server is ready to accept connections |

#### on\_client\_connected

Fired when a client connects to the WebSocket server.

```python theme={null}
@transport.event_handler("on_client_connected")
async def on_client_connected(transport, websocket):
    print("Client connected")
```

**Parameters:**

| Parameter   | Type                       | Description                     |
| ----------- | -------------------------- | ------------------------------- |
| `transport` | `WebsocketServerTransport` | The transport instance          |
| `websocket` | `WebSocketServerProtocol`  | The WebSocket connection object |

#### on\_client\_disconnected

Fired when a client disconnects from the WebSocket server.

```python theme={null}
@transport.event_handler("on_client_disconnected")
async def on_client_disconnected(transport, websocket):
    print("Client disconnected")
```

**Parameters:**

| Parameter   | Type                       | Description                     |
| ----------- | -------------------------- | ------------------------------- |
| `transport` | `WebsocketServerTransport` | The transport instance          |
| `websocket` | `WebSocketServerProtocol`  | The WebSocket connection object |

#### on\_session\_timeout

Fired when a client session exceeds the configured `session_timeout` duration. Only fires if `session_timeout` is set in the params.

```python theme={null}
@transport.event_handler("on_session_timeout")
async def on_session_timeout(transport, websocket):
    print("Session timed out")
```

**Parameters:**

| Parameter   | Type                       | Description                     |
| ----------- | -------------------------- | ------------------------------- |
| `transport` | `WebsocketServerTransport` | The transport instance          |
| `websocket` | `WebSocketServerProtocol`  | The WebSocket connection object |

#### on\_websocket\_ready

Fired when the WebSocket server has started and is ready to accept client connections.

```python theme={null}
@transport.event_handler("on_websocket_ready")
async def on_websocket_ready(transport):
    print("WebSocket server ready")
```

**Parameters:**

| Parameter   | Type                       | Description            |
| ----------- | -------------------------- | ---------------------- |
| `transport` | `WebsocketServerTransport` | The transport instance |

### WebsocketClientTransport Events

#### Events Summary

| Event             | Description                        |
| ----------------- | ---------------------------------- |
| `on_connected`    | Connected to WebSocket server      |
| `on_disconnected` | Disconnected from WebSocket server |

```python theme={null}
@transport.event_handler("on_connected")
async def on_connected(transport, websocket):
    print("Connected to server")

@transport.event_handler("on_disconnected")
async def on_disconnected(transport, websocket):
    print("Disconnected from server")
```

**Parameters:**

| Parameter   | Type                       | Description                     |
| ----------- | -------------------------- | ------------------------------- |
| `transport` | `WebsocketClientTransport` | The transport instance          |
| `websocket` | `WebSocketClientProtocol`  | The WebSocket connection object |

<Note>
  The WebSocket server only supports one client connection at a time. If a new
  client connects while one is already connected, the existing connection will
  be closed.
</Note>

## Additional Resources

* [Events Overview](/api-reference/server/events/overview) - Overview of all events in Pipecat
