# @adonisjs/transmit-client 中文文档

规范地址：https://npmcn.com/package/%40adonisjs/transmit-client/

版本：1\.1\.0
npm 元数据更新时间：2026-01-17T22:31:19.249Z
中文译文更新时间：2026-11-05T18:36:42.846Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40adonisjs/transmit-client
原文对照：https://npmcn.com/package/%40adonisjs/transmit-client/?lang=original
项目主页：https://github.com/adonisjs/transmit-client#readme
源码仓库：https://github.com/adonisjs/transmit-client

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：45.5 kB，12 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.16\.0
- 运行依赖：0 个
- 首次发布：2023-07-07T20:28:33.581Z
- 最新版本发布：2026-01-17T22:31:18.755Z
- 近 30 天下载量：63919（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：17（近 12 个月 1 个）

## 中文简介

AdonisJS的本地服务器-Sent-Event模块的客户端.

## 安装

```sh
npm install @adonisjs/transmit-client
```

也可以使用：`pnpm add @adonisjs/transmit-client`、`yarn add @adonisjs/transmit-client`、`bun add @adonisjs/transmit-client`

## README

# AdonisJS 传输客户端

AdonisJS的本地服务器-Sent-Event(SSE)模块的客户端.

  

[![typescript-image](https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript)](https://www.typescriptlang.org/) [![gh-workflow-image](https://img.shields.io/github/actions/workflow/status/adonisjs/transmit-client/checks.yml?branch=develop&style=for-the-badge)](https://github.com/adonisjs/transmit-client/actions/workflows/checks.yml) [![npm-image](https://img.shields.io/npm/v/@adonisjs/transmit-client.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@adonisjs/transmit-client) [![npm-download-image](https://img.shields.io/npm/dm/@adonisjs/transmit-client?style=for-the-badge)](https://www.npmjs.com/package/@adonisjs/transmit-client) [![license-image](https://img.shields.io/npm/l/@adonisjs/transmit-client?color=blueviolet&style=for-the-badge)](https://npmcn.com/package/%40adonisjs/transmit-client/LICENSE.md)

### [使用量](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-installation) | [检查 AdonisJS](https://adonisjs.com/)

  

* * *

AdonisJS Transmit客户端是AdonisJS的本地服务器-Sent-Event(SSE)模块的客户端. 它建在顶上 [事件来源](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) API并提供一个简单的API来接收来自服务器的事件.

## 目录

-   [安装](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-installation)
-   [使用量](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-usage)
-   [创建订阅](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-creating-a-subscription)
    -   [取消订阅](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-unsubscribing)
    -   [订阅请求](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-subscription-request)
    -   [已认证的事件流](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-authenticated-event-stream)
    -   [自定义 UID 生成器](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-custom-uid-generator)
    -   [重新连接](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-reconnecting)
-   [活动](https://npmcn.com/package/%40adonisjs/transmit-client/#readme-events)

## 安装

从 npm 登记册中安装软件包如下:

```sh
npm i @adonisjs/transmit-client
```

## 使用量

模块显示 `Transmit` class,可以用来连接服务器并收听事件.

```ts
import { Transmit } from '@adonisjs/transmit-client'

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
})
```

## 创建订阅

这个 `subscription` 方法用于创建频道的订阅。 该方法接受频道名称

```ts
const subscription = transmit.subscription('chat/1')
```

那么,你必须打电话给 `create` 用于订阅后端注册的方法.

```ts
await subscription.create()
```

您可以使用 `onMessage` 方法。 您可以在同一订阅上定义尽可能多的听众.

```ts
subscription.onMessage((message) => {
  console.log(message)
})
```

您也可以只听一次使用 `onMessagetOnce` 方法.

```ts
subscription.onMessageOnce((message) => {
  console.log('I will be called only once')
})
```

Note 收听器只属于本地;您可以在服务器注册订阅之前或之后添加它们.

### 取消订阅

这个 `onMessage` 方法返回从订阅中删除信件处理器的函数.

```ts
const unsubscribe = subscription.onMessage(() => {
  console.log('message received!')
})

// later
unsubscribe()
```

如果您想从服务器上完全删除订阅, 您可以拨打 `delete` 方法.

```ts
await subscription.delete()
```

### 订阅请求

您可以使用 `beforeSubscribe` 或者说 `beforeUnsubscribe` 选项.

```ts
const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  beforeSubscribe: (_request: Request) => {
    console.log('beforeSubscribe')
  },
  beforeUnsubscribe: (_request: Request) => {
    console.log('beforeUnsubscribe')
  },
})
```

### 已认证的事件流

这个 `__transmit/events` 使用 `EventSource`,它不能发送自定义标题。 这意味着 `beforeSubscribe`编号 :`beforeUnsubscribe` 只影响订阅/不订阅 HTTP 调用。 如果您依赖基于信头的认证, 请保护 `__transmit/subscribe` 财务报告和审定财务报表 `__transmit/unsubscribe`,或提供习惯 `eventSourceFactory` 可以发送信头.

使用示例 `@microsoft/fetch-event-source`数字 :

```ts
import { fetchEventSource } from '@microsoft/fetch-event-source'

function createFetchEventSource(
  url: string | URL,
  options: { withCredentials: boolean },
  headers: Record<string, string>
) {
  const controller = new AbortController()
  const listeners = new Map<string, Set<(event: MessageEvent) => void>>()

  const dispatch = (type: string, data?: string) => {
    const event = new MessageEvent(type, { data })
    listeners.get(type)?.forEach((listener) => listener(event))
  }

  fetchEventSource(url.toString(), {
    headers,
    credentials: options.withCredentials ? 'include' : 'omit',
    signal: controller.signal,
    onopen: () => dispatch('open'),
    onmessage: (message) => dispatch(message.event ?? 'message', message.data),
    onerror: () => {
      dispatch('error')
    },
  })

  return {
    addEventListener(type: string, listener: (event: MessageEvent) => void) {
      if (!listeners.has(type)) {
        listeners.set(type, new Set())
      }
      listeners.get(type)!.add(listener)
    },
    removeEventListener(type: string, listener: (event: MessageEvent) => void) {
      listeners.get(type)?.delete(listener)
    },
    close() {
      controller.abort()
    },
  } as EventSource
}

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  eventSourceFactory: (url, options) => {
    return createFetchEventSource(url, options, {
      Authorization: `Bearer ${token}`,
    })
  },
})
```

注意: 此适配器是最小的, 只有电线 `open`, (中文(简体) ), `error`,以及 `message` (或自定义事件名称). 如果你依赖别人 `EventSource` 功能类 `readyState` 或者说 `onopen`,你可能想要扩展它.

### 自定义 UID 生成器

默认情况下, 传输使用 `crypto.randomUUID()` 生成唯一的客户端标识符。 这种方法只在 [安全环境](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS) (韩语). 如果您需要通过 HTTP 传输( 例如本地网络部署) , 您可以提供自定义 `uidGenerator` 函数.

```ts
const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  uidGenerator: () => {
    return Array.from({ length: 16 }, () =>
      Math.floor(Math.random() * 256).toString(16).padStart(2, '0')
    ).join('')
  },
})
```

或者利用图书馆 `uuid`数字 :

```ts
import { v4 as uuid } from 'uuid'

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  uidGenerator: () => uuid(),
})
```

### 重新连接

传输客户端将在连接丢失时自动重接服务器. 可以改变重试和钩入重联生命周期的次数如下:

```ts
const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  maxReconnectionAttempts: 5,
  onReconnectAttempt: (attempt) => {
    console.log('Reconnect attempt ' + attempt)
  },
  onReconnectFailed: () => {
    console.log('Reconnect failed')
  },
})
```

# 活动

这个 `Transmit` 类使用 [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) 类以释放多个事件.

```ts
transmit.on('connected', () => {
  console.log('connected')
})

transmit.on('disconnected', () => {
  console.log('disconnected')
})

transmit.on('reconnecting', () => {
  console.log('reconnecting')
})
```

这意味着您也可以通过通过事件听器本身的功能来去除先前注册的事件听器.

```ts
const onConnected = () => {
  console.log('connected')
}

transmit.on('connected', onConnected)
transmit.off('connected', onConnected)
```

## 常见问题

### @adonisjs/transmit-client 是什么？

AdonisJS的本地服务器-Sent-Event模块的客户端\.

### 如何安装 @adonisjs/transmit-client？

在项目目录运行 npm install @adonisjs/transmit-client，或使用 pnpm add / yarn add / bun add。

### @adonisjs/transmit-client 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @adonisjs/transmit-client 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @adonisjs/transmit-client 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.16\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @adonisjs/transmit-client 可以商用吗？

@adonisjs/transmit-client 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @adonisjs/transmit-client 的下载量有多少？

根据 npm 官方下载统计，@adonisjs/transmit-client 在 2026/10/05 – 2026/11/03 这 30 天内被下载 63,919 次，日均约 2,131 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @adonisjs/transmit-client 还在维护吗？

最新版本 1\.1\.0 发布于 2026/01/18（9 个月前）；至今共发布 17 个版本，其中过去 12 个月发布了 1 个；首次发布于 2023/07/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

