#背景
- 产品通信方式改为
WebSocket
- 后端使用原生写
- 目前业务只接收信息
拿到需求的时候马上想到了socket.io
库,因此没想太多就测试使用了,但是测试发现一直连接失败,debugger一天一直没解决,后来才从socket.io
文档上发现了问题,害,以后得好好看文档。
根据socket.io
推荐的客户端封装robust-websocket(opens new window)已经好久没有更新了,同时该库使用ES5
写法,不符合当前要求,因此决定自己封装一个。
#封装
目前的需求其实就是前端接收信息即可,因此就做了简单的封装,以下是封装时考虑到的几点:
- 实现发布订阅功能
- 支持单例
- 连接时存在超时时间
- 支持断开重连并且支持配置重连次数
其中部分API参考了socket.io
#基础模板
询问chatGPT
可以得到初始模板
interface WebSocketOptions {
url: string;
timeout?: number;
reconnectTimes?: number;
}
type WebSocketEvent = 'open' | 'close' | 'message' | 'error';
class WebSocketClient {
private static instance: WebSocketClient;
private ws: WebSocket | null = null;
private url: string;
private timeout: number;
private reconnectTimes: number;
private eventListeners: Map<WebSocketEvent, Set<Function>> = new Map();
private constructor(options: WebSocketOptions) {
this.url = options.url;
this.timeout = options.timeout || 5000;
this.reconnectTimes = options.reconnectTimes || 3;
this.connect();
}
public static getInstance(options: WebSocketOptions): WebSocketClient {
if (!WebSocketClient.instance) {
WebSocketClient.instance = new WebSocketClient(options);
}
return WebSocketClient.instance;
}
public on(event: WebSocketEvent, listener: Function): void {
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, new Set());
}
this.eventListeners.get(event)?.add(listener);
}
public off(event: WebSocketEvent, listener: Function): void {
if (this.eventListeners.has(event)) {
this.eventListeners.get(event)?.delete(listener);
}
}
public emit(event: WebSocketEvent, data: any): void {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ event, data }));
}
}
private connect(): void {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
this.eventListeners.get('open')?.forEach((listener) => listener());
};
this.ws.onclose = () => {
this.eventListeners.get('close')?.forEach((listener) => listener());
if (this.reconnectTimes > 0) {
this.reconnectTimes--;
setTimeout(() => this.connect(), this.timeout);
}
};
this.ws.onmessage = (event) => {
const { event: eventName, data } = JSON.parse(event.data);
this.eventListeners.get(eventName)?.forEach((listener) => listener(data));
};
this.ws.onerror = () => {
this.eventListeners.get('error')?.forEach((listener) => listener());
};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#发布订阅功能
interface ClientOptions {
autoConnect: boolean;
protocols?: string[];
}
type EventFunc = (event: any) => void;
const enum WebSocketEventEnum {
open = 'open',
close = 'close',
error = 'error',
message = 'message'
}
const getDefaultOptions = (): ClientOptions => ({
autoConnect: true
});
const getEmptyEventsMap = (): Record<WebSocketEventEnum, EventFunc[]> => ({
[WebSocketEventEnum.open]: [],
[WebSocketEventEnum.close]: [],
[WebSocketEventEnum.error]: [],
[WebSocketEventEnum.message]: [],
});
class WebsocketClient {
private url: string;
private options: ClientOptions;
private websocket: WebSocket | null;
private events = getEmptyEventsMap();
constructor(url: string, options: Partial<ClientOptions>) {
this.url = url;
this.options = {
...getDefaultOptions(),
...options
};
if (this.options.autoConnect) {
this.connect();
}
}
public connect() {
this.websocket = new WebSocket(this.url, this.options.protocols);
this.websocket.onopen = (event) => {
this.emit(WebSocketEventEnum.open, event);
}
this.websocket.onmessage = (event) => {
this.emit(WebSocketEventEnum.message, event);
}
this.websocket.onerror = (event) => {
this.emit(WebSocketEventEnum.error, event);
}
this.websocket.onclose = (event) => {
this.emit(WebSocketEventEnum.close, event);
}
}
public on(name: WebSocketEventEnum, listener: EventFunc) {
this.events[name].push(listener);
}
public off(name?: WebSocketEventEnum, listener?: EventFunc) {
if (!name) {
this.events = getEmptyEventsMap();
return;
}
if (!listener) {
this.events[name] = [];
return;
}
const index = this.events[name].findIndex(fn => fn === listener);
if (index > -1) {
this.events[name].splice(index, 1);
}
}
public send (data: string | ArrayBuffer | SharedArrayBuffer | Blob | ArrayBufferView) {
if (this.websocket?.readyState === WebSocket.OPEN) {
this.websocket.send(data);
}
}
private emit(name: WebSocketEventEnum, event: any) {
this.events[name].forEach(listener => listener(event));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#支持单例
考虑到如果某一个websocket状态如果与某一个文件强关联那么可以把事件直接注册到那个文件中,为了避免创建多个实例,所以考虑加一个单例功能
class WebSocketClient {
private static instance: WebsocketClient | null = null;
public static getInstance(url: string, options: Partial<ClientOptions> = {}) {
if (!WebsocketClient.instance) {
WebsocketClient.instance = new WebsocketClient(url, options);
}
return WebsocketClient.instance;
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
#设置超时时间
interface ClientOptions {
// ...
timeout: number;
}
const getDefaultOptions = (): ClientOptions => ({
// ...
timeout: 20_000,
});
class WebSocketClient {
public connect() {
this.websocket = new WebSocket(this.url, this.options.protocols);
this.setTimer();
this.websocket.onopen = (event) => {
this.clearTimer();
this.emit(WebSocketEventEnum.open, event);
}
// ...
}
private setTimer() {
this.clearTimer();
this.timer = setTimeout(() => {
// 疑问1
this.websocket?.close();
}, this.options.timeout);
}
private clearTimer() {
this.timer !== null && clearTimeout(this.timer);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#断开重连
interface ClientOptions {
// ...
reconnectionAttempts: number;
reconnectionDelay: number;
}
const enum WebSocketEventEnum {
// ...
reconnectAttempt = 'reconnectAttempt',
reconnectFailed = 'reconnectFailed'
}
const getDefaultOptions = (): ClientOptions => ({
// ...
reconnectionAttempts: Infinity,
reconnectionDelay: 5_000,
});
class WebSocketClient {
private reconnectionAttempts = 0;
public connect(resetReconnectionAttempts = true) {
// 手动调用默认重置重连,但是内部调用不需要清空
if (resetReconnectionAttempts) {
this.reconnectionAttempts = 0;
}
// ...
this.websocket.onerror = (event) => {
this.emit(WebSocketEventEnum.error, event);
this.reconnect(event);
}
this.websocket.onclose = (event) => {
this.emit(WebSocketEventEnum.close, event);
this.reconnect(event);
}
}
public disconnect() {
this.reconnectionAttempts = -1;
this.websocket?.close(1_000, 'Normal Closure');
}
private reconnect (event: Event) {
// -1时不需要重连
if (this.reconnectionAttempts === -1) {
this.websocket = null;
return;
}
// 疑问2
if (this.websocket?.readyState !== WebSocket.CLOSED) {
return;
}
this.websocket = null;
this.reconnectionAttempts++;
this.emit(WebSocketEventEnum.reconnectAttempt, this.reconnectionAttempts);
if (!Number.isFinite(this.options.reconnectionAttempts) || this.reconnectionAttempts <= this.options.reconnectionAttempts) {
setTimeout(() => {
this.connect(false);
}, this.options.reconnectionDelay);
return;
}
this.emit(WebSocketEventEnum.reconnectFailed, event);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#其他
其实还可以增加once
功能,只触发一次,这里的逻辑和on类似,因此不再列举
#问题
在上面的代码中引申出两个问题
#疑问1
在超时时间中我直接使用了this.websocket?.close()
,根据MDN(opens new window)中的语法来说存在code
和reason
- 默认打印出的
code
和reason
是什么 - 如果我在代码中手动赋值,那么打印出的
code
和reason
是什么,是默认值还是手动赋的值
#疑问2
- 如果我直接设置
this.websocket = null
不加前面的判断会出现什么结果
下一篇解答,敬请期待...