Skip to content

Commit e8f2320

Browse files
author
shenweijie
committed
add readme
1 parent 3a87df0 commit e8f2320

File tree

2 files changed

+91
-1
lines changed

2 files changed

+91
-1
lines changed

README.md

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# light-websocket-client-ts
2+
3+
轻量封装 Websocket 客户端 ts 版
4+
5+
## 简介
6+
7+
一个基于 Websocket 进行简单封装的轻量协议客户端,需配合 `light-websocket-server` 使用
8+
9+
### 1. 连接保活
10+
11+
由于 websocket 的 js API 无法发送 websocket 的 ping 帧,导致只能在应用层协议再实现一遍保活机制,所以此协议在 `DataFame` 首部分出一个字节作为协议头,实现了相对 websocket 协议更上层,但是相对应用层更下层的保活机制
12+
13+
### 2. 自动重连
14+
15+
- 自动重连默认开启,可以通过 Options 来进一步控制
16+
- 客户端主动调用 disconnect() 关闭连接会禁用自动重连,直到重新调用 connect()
17+
- 自动重连采用退避超时策略,可以通过 Options 来进一步控制
18+
19+
## 快速开始
20+
21+
### 浏览器
22+
23+
- 安装依赖
24+
25+
```sh
26+
$ npm install light-websocket-client-ts --saved
27+
```
28+
29+
- 创建连接
30+
31+
```typescript
32+
const client = new LightWebsocketCLientImpl('ws://xxx/xxx');
33+
client.onDisconnect(onDisconnect);
34+
client.onConnect(onConnect);
35+
client.onMessage(onMessage);
36+
37+
client.connect();
38+
39+
function onConnect() {
40+
}
41+
42+
function onDisconnect() {
43+
}
44+
45+
function onMessage(message: string) {
46+
}
47+
```
48+
49+
### Node.js 端
50+
51+
- 安装依赖
52+
53+
```sh
54+
$ npm install light-websocket-client-ts --saved
55+
$ npm install ws --saved
56+
```
57+
58+
- 创建 Node.js ws 实现
59+
60+
```typescript
61+
import {LightWebsocketClientImpl} from 'light-websocket-client-ts';
62+
import * as Websocket from 'ws';
63+
64+
export class LightWebsocketCLientNodeImpl extends LightWebsocketClientImpl {
65+
66+
createWebsocket(url: string, protocols?: string[] | undefined): any {
67+
return new Websocket(url, protocols, {});
68+
}
69+
}
70+
````
71+
72+
- 使用 Node.js 实现创建连接
73+
74+
```typescript
75+
const client = new LightWebsocketCLientNodeImpl('ws://xxx/xxx');
76+
client.onDisconnect(onDisconnect);
77+
client.onConnect(onConnect);
78+
client.onMessage(onMessage);
79+
80+
client.connect();
81+
82+
function onConnect() {
83+
}
84+
85+
function onDisconnect() {
86+
}
87+
88+
function onMessage(message: string) {
89+
}
90+
```

test/CookieNodeLightWebsocketClient.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ describe('test', () => {
55
// beforeEach(() => {
66
// this.setTimeout(done, 0);
77
// });
8-
const client = new CookieNodeLightWebsocketClient('http://localhost:8080/push/endpoint?csrf=Jk38deaiEe28oobm636OOA');
8+
const client = new CookieNodeLightWebsocketClient('ws://localhost:8080/push/endpoint?csrf=Jk38deaiEe28oobm636OOA');
99
client.onDisconnect(onClose);
1010
client.onConnect(onOpen);
1111
client.onMessage(onMessage);

0 commit comments

Comments
 (0)