# @fakehost/exchange 中文文档

规范地址：https://npmcn.com/package/%40fakehost/exchange/

版本：1\.0\.0-beta\.2
npm 元数据更新时间：2023-10-04T08:36:03.049Z
中文译文更新时间：2026-11-14T09:13:27.474Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40fakehost/exchange
原文对照：https://npmcn.com/package/%40fakehost/exchange/?lang=original

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

- 包体积（解压后）：151 kB，72 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：7 个
- 首次发布：2021-09-02T08:54:44.231Z
- 最新版本发布：2023-10-04T08:36:02.845Z
- 近 30 天下载量：23364（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：28（近 12 个月 0 个）

## 中文简介

用于构建通过websockets通信的假消息服务的基本包. 可以作为节点服务运行,也可以被捆绑在浏览器内部.

## 安装

```sh
npm install @fakehost/exchange
```

也可以使用：`pnpm add @fakehost/exchange`、`yarn add @fakehost/exchange`、`bun add @fakehost/exchange`

## README

# @ fakehost/ 交换

[![NPM Version](https://img.shields.io/npm/v/@fakehost/exchange.svg)](https://npmjs.org/package/@fakehost/exchange)

## 概览

**[更多信息见文件.](https://ilikejames.github.io/fakehost)**

用于构建通过websockets通信的假消息服务的基本包. 可以作为节点服务运行,也可以被捆绑在浏览器内部.

**这个图书馆不会给你太多 自己.** 相反,它被用来支持运行 相同的假服务代码托管 **浏览器内部** 或者说 **作为节点进程运行**。 。 。 .

提供两个主要对象:

-   `WsHost`。用于启动网络安全套服务。 它作为一个节点进程运行,它可以从命令行开始,或者从节点测试,例如:快活、活生生、剧作家、网络司机等开始.
-   `BrowserWsHost`. 用于启动"被嘲笑"的websocket服务. 这直接运行在浏览器内部,对于将"假"服务捆绑在"故事本"内部,或演示应用程序,以及运行Cypress等基于浏览器的测试都是有益的.

**不要在生产环境中使用这个。 这是用来测试的 只能做演示.**

## 示例使用

完整的例子见 [@ fakehost/ 假信号](https://github.com/ilikejames/fakehost/tree/master/packages/signalr/fake-signalr)。 。 。 .

### 协议处理器

信使服务有多种不同类型的协议来管理信息交换. 其中许多是习俗.

假设我们正在构建一个假协议处理器,用于一个具有以下消息和发出消息结构的服务:

```typescript
type IncomingMessage = {
    destination: string
    payload: unknown
}

type OutgoingMessage = {
    destination: string
    payload: unknown
}
```

消息全部在JSON中,因此我们可以通过检查网络分页和查看消息来方便地检查服务在做什么.

一个仅支持简单请求/答复消息的极基本协议可能看起来像:

```typescript
import { Host, ConnectionId, Connection, ExchangeEvent } from '@fakehost/exchange'

type MessageHandler = (payload: unknown) => unknown

export class MyProtocolHandler {

    private messageHandlers = new Map<string, MessageHandler>()

    constructor(host: Host) {
        host.on('connection', this.onConnection.bind(this))
        host.on('disconnection', this.onDisconnection.bind(this))
        host.on('message', this.onMessage.bind(this))
    }

    onConnection({ connection }: ExchangeEvent<'connection'>) {
        console.log(`a new connection "${connection.id}"`)
    }

    onDisconnection({ connection }: ExchangeEvent<'disconnect'>) {
        console.log(`connection "${connection.id}" has disconnected`)
    }

    onMessage({ connection, message: rawMessage }: ExchangeEvent<'message'>) {
        // deserialize the incoming message
        const message: IncomingMessage = this.deserialize(rawMessage)

        // get the handler for the service + method
        const handler = this.messageHandlers.get(message.destination)

        if(!handler) {
            console.log(`"${destination}" not handled`)
            return
        }

        // call the handler
        const result = handler(message.payload)

        // send the handler's response
        connection.write(JSON.stringify({
            destination: message.destination,
            payload: result
        }))
    }

    deserialize(message: string | Buffer) {
        const parsed = typeof message === 'string' ? message : new TextDecoder('utf-8').decode(message);
        return JSON.parse(parsed) as IncomingMessage;
    }

    register(destination: string, handler: MessageHandler) {
        this.messageHandlers.set(destination, handler)
    }
}
```

并让电线 处理器,开始 `MyProtocolHandler` 作为本地主机服务运行 :

```typescript
import { WsHost } from '@fakehost/exchange'

// start a websocket service listening on port 5000 at /json
const host = new WsHost({
    name: 'fake',
    debug: true,
    port: 5000,
    path: '/json'
})

// create a new protocol handler
const protocol = new MyProtocolHandler(host)

// create a simple handler and register it to handle incoming messages with destination of `greeting`
const greetingHandler = (payload: { name: string }) => {
    return `Hello, ${name}!`
}
protocol.register('greeting', greetingHandler)
```

## 调试

调试日志可以通过构造器或环境变量启用:

```sh
DEBUG=@fakehost/exchange
```

## 许可证

@ fakehost/ 交换机根据 [MIT 许可证](https://mit-license.org/)。 。 。 .

## 从 v.x 移动

见 [从 v.x 移动](https://ilikejames.github.io/fakehost/#/exchange/migrating-from-v0.md)

## 常见问题

### @fakehost/exchange 是什么？

用于构建通过websockets通信的假消息服务的基本包\. 可以作为节点服务运行,也可以被捆绑在浏览器内部\.

### 如何安装 @fakehost/exchange？

在项目目录运行 npm install @fakehost/exchange，或使用 pnpm add / yarn add / bun add。

### @fakehost/exchange 支持 TypeScript 吗？

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

### @fakehost/exchange 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @fakehost/exchange 可以商用吗？

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

### @fakehost/exchange 的下载量有多少？

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

### @fakehost/exchange 还在维护吗？

最新版本 1\.0\.0-beta\.2 发布于 2023/10/04（3 年前）；至今共发布 28 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/09/02。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

