> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/websocket-chuan-shu-ceng.md).

# WebSocket 传输层

WebSocket 传输在受 WebRTC 限制的移动 webview、阻止 UDP 的企业网络，或任何不支持 WebRTC 的平台上都很有用。它底层使用 Pipecat，并且完全按需启用——除非你显式导入传输子路径，否则 pipecat 包绝不会被打包。

***

### 何时使用 WebSocket 传输

| 情况                         | 建议                       |
| -------------------------- | ------------------------ |
| 标准 Web 应用                  | WebRTC（默认）— 更低延迟，更好的音频质量 |
| 受 WebRTC 限制的移动 webview     | WebSocket                |
| 阻止 UDP/STUN/TURN 的企业网络     | WebSocket                |
| Bundle 中不得包含 `@pipecat-ai` | WebRTC（默认——无需额外导入）       |
| 回退或测试路径                    | WebSocket                |

***

### 设置

WebSocket 传输是 **按需启用**. pipecat 包（`@pipecat-ai/client-js`, `@pipecat-ai/websocket-transport`）绝不会被打包，除非你显式导入传输子路径。

#### React

```tsx
// 1. 注册传输——必须在调用 connect() 之前导入
import '@convai/web-sdk/vanilla/websocket';

import { useConvaiClient, ConvaiWidget } from '@convai/web-sdk/react';

export default function App() {
  const client = useConvaiClient({
    apiKey: '...',
    characterId: '...',
    transport: 'websocket',
  });

  return <ConvaiWidget convaiClient={client} />;
}
```

#### 原生 JS

```ts
// 1. 注册传输
import '@convai/web-sdk/vanilla/websocket';

import { ConvaiClient } from '@convai/web-sdk/vanilla';
import { createConvaiWidget } from '@convai/web-sdk/vanilla';

const client = new ConvaiClient({
  apiKey: '...',
  characterId: '...',
  transport: 'websocket',
});

createConvaiWidget(document.body, { convaiClient: client as any });
```

导入顺序很重要——构造客户端之前必须先注册。

***

### 包隔离

`ConvaiClient` 本身不包含任何 pipecat 导入。WebSocket 实现完全位于 `@convai/web-sdk/vanilla/websocket` 子路径中。未看到导入该子路径的打包工具（Vite、webpack、Rollup）不会将 `@pipecat-ai/client-js` 或 `@pipecat-ai/websocket-transport` 添加到任何 chunk 中。

```
@convai/web-sdk/vanilla         → 零 pipecat 代码
@convai/web-sdk/react           → 零 pipecat 代码
@convai/web-sdk/vanilla/websocket → pipecat 代码（仅按需启用）
```

如果您调用 `connect()` 其带有 `transport: "websocket"` 在未先导入子路径的情况下，SDK 会抛出清晰的错误：

```
[ConvaiClient] WebSocket 传输未注册。
在调用 connect() 之前添加 `import '@convai/web-sdk/vanilla/websocket'`。
```

***

### 功能对比

| 功能               | WebRTC（默认） | WebSocket  |
| ---------------- | ---------- | ---------- |
| 无需 UDP 即可工作      | ✗          | ✓          |
| 需要 `@pipecat-ai` | ✗          | ✓（按需启用子路径） |
| 移动 webview 支持    | 因平台而异      | 更好         |

{% hint style="info" %}
WebSocket 传输层的文件上传：即将推出
{% endhint %}

***

### 麦克风行为

在 WebRTC 下，麦克风会通过以下方式显式激活： `audioControls.enableAudio()` 或 `startWithAudioOn` 配置标志。

在 WebSocket 下，Pipecat 传输会在……期间初始化音频流。 `connect()`SDK 在连接时默认开启麦克风，并会在 `startWithAudioOn: false`:

```ts
// 麦克风初始为静音——用户可通过小组件或 audioControls 取消静音
const client = new ConvaiClient({
  transport: 'websocket',
  startWithAudioOn: false,
  ...
});
```

***

### API 参考

#### Config

| 字段          | 类型                         | 默认值         | 说明                                                 |
| ----------- | -------------------------- | ----------- | -------------------------------------------------- |
| `transport` | `"livekit" \| "websocket"` | `"livekit"` | 默认使用 WebRTC； `"websocket"` 选择 Pipecat WebSocket 传输 |

#### 静态方法

```ts
import { ConvaiClient } from '@convai/web-sdk/vanilla';

// 由 websocket 子路径导入自动调用。
// 仅在你注册自定义的 WebSocket 传输实现时需要。
ConvaiClient.registerWebSocketTransport(factory);
```

`registerWebSocketTransport` 接受一个签名如下的工厂函数：

```ts
(onMessage: (payload: Uint8Array) => void, enableMic: boolean) => IWebSocketSession
```

如果需要，这让你可以替换为自定义的 WebSocket 会话实现。


---

# 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:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/websocket-chuan-shu-ceng.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
