Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 42 additions & 36 deletions docs/docs/get-started/realtime-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,43 +9,44 @@ TSRPC 的二进制序列化特性,能显著减小包体,帮助实时服务
你可以通过 `npx create-tsrpc-app@latest` 快速创建一个 WebSocket 实时聊天室项目。

## 实时 API

TSRPC 本身的设计架构是协议无关的,这意味着在[上一节](the-first-api.md)中实现的 API 可以无缝运行在 WebSocket 协议之上。
只需要将 `HttpServer` 替换为 `WebSocketServer`,将 `HttpClient` 替换为 `WebSocketClient` 即可。例如:

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs
defaultValue="server"
values={[
{label: 'Server', value: 'server'},
{label: 'Client', value: 'client'}
]}>
<TabItem value="server">
defaultValue="server"
values={[
{label: 'Server', value: 'server'},
{label: 'Client', value: 'client'}
]}>
<TabItem value="server">

```ts
import { WsServer } from 'tsrpc';
import { WsServer } from 'tsrpc'

const server = new WsServer(serviceProto, {
port: 3000
});
port: 3000,
})
```

</TabItem>

<TabItem value="client">

```ts
import { WsClient } from 'tsrpc-browser';
import { WsClient } from 'tsrpc-browser'

const client = new WsClient(serviceProto, {
server: 'ws://127.0.0.1:3000',
logger: console
});
server: 'ws://127.0.0.1:3000',
logger: console,
})

let ret = await client.callApi('Hello', {
name: 'World'
});
let ret = await client.callApi('Hello', {
name: 'World',
})
```

</TabItem>
Expand All @@ -68,12 +69,13 @@ let ret = await client.callApi('Hello', {

```ts title="MsgChat.ts"
export interface MsgChat {
name: string,
name: string
content: string
}
```

跟 API 协议一样,新增或修改消息定义后,也应该重新生成 ServiceProto,然后同步到前端项目。

```shell
cd backend
npm run proto
Expand All @@ -85,21 +87,24 @@ npm run sync
消息可以双向传递,即可以从 Server 发给 Client,也可以从 Client 发给 Server。

#### Client 发送

```ts
client.sendMsg('Chat', {
name: 'k8w',
content: 'I love TSRPC.'
content: 'I love TSRPC.',
})
```

#### Server 发送

Server 同时可能连接着多个 Client,活跃中的所有连接都在 `server.conns`。
要给其中某个 Client 发送消息,可以使用 `conn.sendMsg` ,例如:

```ts
// 给第一个连接的 Client 发送消息
server.conns[0].sendMsg('Chat', {
name: 'System',
content: 'You are the first connection.'
content: 'You are the first connection.',
})
```

Expand All @@ -110,10 +115,11 @@ server.conns[0].sendMsg('Chat', {
#### Server 广播

要给所有 Client 发送消息,可以使用 `server.broadcastMsg()`,例如:

```ts
server.broadcastMsg('Chat', {
name: 'System',
content: 'This is a message to everyone.'
content: 'This is a message to everyone.',
})
```

Expand All @@ -124,21 +130,21 @@ server.broadcastMsg('Chat', {
监听 / 解除监听消息在 Server 和 Client 类似,例子如下:

<Tabs
defaultValue="server"
values={[
{label: 'Server', value: 'server'},
{label: 'Client', value: 'client'}
]}>
<TabItem value="server">
defaultValue="server"
values={[
{label: 'Server', value: 'server'},
{label: 'Client', value: 'client'}
]}>
<TabItem value="server">

```ts
// 监听(会返回传入的处理函数)
let handler = server.listenMsg('Chat', call=>{
server.broadcastMsg('Chat', call.msg);
});
let handler = server.listenMsg('Chat', (call) => {
server.broadcastMsg('Chat', call.msg)
})

// 取消监听
server.unlistenMsg('Chat', handler);
server.unlistenMsg('Chat', handler)
```

</TabItem>
Expand All @@ -147,24 +153,24 @@ server.unlistenMsg('Chat', handler);

```ts
// 监听(会返回传入的处理函数)
let handler = client.listenMsg('Chat', msg=>{
console.log(msg.name, msg.content);
});
let handler = client.listenMsg('Chat', (msg) => {
console.log(msg.name, msg.content)
})

// 取消监听
client.unlistenMsg('Chat', handler);
client.unlistenMsg('Chat', handler)
```

</TabItem>
</Tabs>

不同之处在于,由于 Server 同时可能连接着多个 Client,所以监听消息时收到的参数为 `call: MsgCall`。
其中除了消息内容( `call.msg` )外,还包含Client 连接( `call.conn` )等信息。
其中除了消息内容( `call.msg` )外,还包含 Client 连接( `call.conn` )等信息。

而 Client 由于只存在唯一的连接,故监听消息时,收到的参数即为消息本身:`msg: MsgXXXX`。

## 例子:实时聊天室

使用 `npx create-tsrpc-app@latest` 创建一个带浏览器前端的 WebSocket 项目,里面已经自带了一个极简的聊天室的例子,你也可以在这里查看:

https://github.com/k8w/tsrpc-examples/tree/main/examples/chatroom
https://github.com/k8w/tsrpc-examples/tree/main/examples/chatroom
31 changes: 20 additions & 11 deletions docusaurus.config.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
/** @type {import('@docusaurus/types').DocusaurusConfig} */
module.exports = {
title: 'TSRPC - TypeScript 跨平台 RPC 框架',
tagline: '目前世界上唯一支持 TypeScript 复杂类型\n运行时自动检测和二进制序列化的\nTypeScript 开源 RPC 框架',
tagline:
'目前世界上唯一支持 TypeScript 复杂类型\n运行时自动检测和二进制序列化的\nTypeScript 开源 RPC 框架',
url: 'https://tsrpc.cn',
baseUrl: '/',
onBrokenLinks: 'throw',
onBrokenLinks: 'warn',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/favicon.ico',
organizationName: 'k8w', // Usually your GitHub org/user name.
projectName: 'tsrpc', // Usually your repo name.
i18n: {
defaultLocale: 'zh-cn',
locales: ['zh-cn', 'en'],
},
themeConfig: {
colorMode: {
defaultMode: 'light',
disableSwitch: true,
respectPrefersColorScheme: false
respectPrefersColorScheme: false,
},
navbar: {
title: 'TSRPC',
Expand Down Expand Up @@ -41,9 +46,13 @@ module.exports = {
label: '示例',
},
// { to: '/blog', label: 'Blog', position: 'left' },
{
type: 'localeDropdown',
position: 'right',
},
{
label: 'v3.0.4', // by default, show active/latest version label
position: 'right'
position: 'right',
},
{
href: 'https://github.com/k8w/tsrpc',
Expand Down Expand Up @@ -113,7 +122,7 @@ module.exports = {
// Please change this to your repo.
// editUrl:
// 'https://github.com/k8w/tsrpc-docs/blob/main/',
routeBasePath: '/'
routeBasePath: '/',
},
// blog: {
// showReadingTime: true,
Expand All @@ -130,7 +139,7 @@ module.exports = {
plugins: [
function baiduTongJi(context, options) {
if (process.env.NODE_ENV !== 'production') {
return {};
return {}
}
return {
name: 'docusaurus-plugin-baidu-analytics',
Expand All @@ -148,9 +157,9 @@ module.exports = {
})();`,
},
],
};
}
},
};
}
]
};
}
},
],
}
67 changes: 67 additions & 0 deletions i18n/en/docusaurus-plugin-content-docs/current/api/http-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
sidebar_position: 2
---

# HttpClient

## HttpClientOptions

Configuration options when creating HttpClient.

| field | type | default | description |
| :-----------: | :-------: | :-----------------------: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **server** | `string` | `"http://127.0.0.1:3000"` | Server URL, 以 `http://` 或 `https://` 开头。 |
| **json** | `boolean` | `false` | Enables or disables JSON transfer mode, which will use JSON strings instead of binary serialized transfers. Requires the Server to also enable the jsonEnabled option. |
| **jsonPrune** | `boolean` | `true` | When using JSON transfer mode, whether to automatically exclude extra fields that do not exist in the protocol during the runtime type detection phase. For security reasons, it is always recommended to turn this on. |
| **logger** | `Logger` | `undefined` | Network communication such as API requests/responses will be output to the specified `Logger`. This can be set to `console` if you need to print the log to the console, or to `undefined` if you need to hide the log. |
| **timeout** | `number` | `undefined` | Timeout for API requests in milliseconds, `undefined` or `0` means no time limit. |
| **debugBuf** | `boolean` | `false` | Whether or not to print the binary transfer information in the log, which will make it easier to debug when you develop binary transfer encryption. |

```ts
export interface HttpOptions {
/**
* Server URL, 以 `http://` 或 `https://` 开头。
* 默认:"http://127.0.0.1:3000"
*/
server: string

/**
* 是否启用 JSON 传输模式,启用后将使用 JSON 字符串替代二进制序列化传输。(也进行运行时类型检测)
* 注意:需要 Server 也开启 `jsonEnabled` 选项。
* 默认:false
*/
json: boolean

/**
* 使用 JSON 传输模式时,在运行时类型检测阶段,是否自动剔除协议中不存在的额外字段。
* 出于安全性考虑,建议总是开启,需要动态字段的协议可以通过索引签名定义:
* {
* aaa: string,
* bbb: number,
* // 通过索引签名允许额外字段
* [key: string]: any
* }
* 默认:true
*/
jsonPrune: boolean

/**
* API 请求/响应 等网络通讯情况,将被输出至指定的 `Logger` 中。
* 如果需要将日志打印到控制台,可以设为 `console`;如果需要隐藏日志,可以设为 `undefined`。
* 默认:`undefined` (这以为着如果你不设置 `logger`,则通讯细节会被隐藏,这有利于防止破解和提升安全性。)
*/
logger?: Logger

/**
* API 请求的超时时间(毫秒),`undefined` 或 `0` 意味不限时。
* 默认:`undefined`
*/
timeout?: number
/**
* 是否将二进制传输信息打印在日志中。
* 当你开发二进制传输加密时,这些信息会便于你调试。
* 默认:false
*/
debugBuf?: boolean
}
```
9 changes: 9 additions & 0 deletions i18n/en/docusaurus-plugin-content-docs/current/api/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
sidebar_position: 1
---

# API

:::danger WIP
This document is still in preparation ...... Stay tuned.
:::
45 changes: 45 additions & 0 deletions i18n/en/docusaurus-plugin-content-docs/current/api/ws-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
sidebar_position: 3
---

# WsClient

## WsClientOptions

创建 `WsClient` 时的配置选项。

| 字段名 | 类型 | 默认值 | 描述 |
| :-: | :-: | :-: | - |
| **server** | `string` | `"ws://127.0.0.1:3000"` | Server URL, 以 `ws://` 或 `wss://` 开头。 |
| **logger** | `Logger` | `undefined` | API 请求/响应 等网络通讯情况,将被输出至指定的 `Logger` 中。如果需要将日志打印到控制台,可以设为 `console`;如果需要隐藏日志,可以设为 `undefined`。 |
| **timeout** | `number` | `undefined` | API 请求的超时时间(毫秒),`undefined` 或 `0` 意味不限时。 |
| **debugBuf** | `boolean` | `false` | 是否将二进制传输信息打印在日志中,当你开发二进制传输加密时,这些信息会便于你调试。 |

```ts
export interface HttpOptions {
/**
* Server URL, 以 `ws://` 或 `wss://` 开头。
* 默认:"ws://127.0.0.1:3000"
*/
server: string;

/**
* API 请求/响应 等网络通讯情况,将被输出至指定的 `Logger` 中。
* 如果需要将日志打印到控制台,可以设为 `console`;如果需要隐藏日志,可以设为 `undefined`。
* 默认:`undefined` (这以为着如果你不设置 `logger`,则通讯细节会被隐藏,这有利于防止破解和提升安全性。)
*/
logger?: Logger;

/**
* API 请求的超时时间(毫秒),`undefined` 或 `0` 意味不限时。
* 默认:`undefined`
*/
timeout?: number;
/**
* 是否将二进制传输信息打印在日志中。
* 当你开发二进制传输加密时,这些信息会便于你调试。
* 默认:false
*/
debugBuf?: boolean
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Cookbook

:::danger WIP
此文档还在编写中…… 敬请期待。
:::
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Client-side development",
"position": 3
}
Loading