-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathsocket.ts
172 lines (134 loc) · 3.53 KB
/
socket.ts
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { EventEmitter } from "eventemitter3";
import logger from "./logger";
import { ServerMessageType, SocketEventType } from "./enums";
import { version } from "../package.json";
/**
* An abstraction on top of WebSockets to provide fastest
* possible connection for peers.
*/
export class Socket extends EventEmitter {
private _disconnected: boolean = true;
private _id?: string;
private _messagesQueue: Array<object> = [];
private _socket?: WebSocket;
private _wsPingTimer?: any;
private readonly _baseUrl: string;
constructor(
secure: any,
host: string,
port: number,
path: string,
key: string,
private readonly pingInterval: number = 5000,
) {
super();
const wsProtocol = secure ? "wss://" : "ws://";
this._baseUrl = wsProtocol + host + ":" + port + path + "peerjs?key=" + key;
}
start(id: string, token: string): void {
this._id = id;
const wsUrl = `${this._baseUrl}&id=${id}&token=${token}`;
if (!!this._socket || !this._disconnected) {
return;
}
this._socket = new WebSocket(wsUrl + "&version=" + version);
this._disconnected = false;
this._socket.onmessage = (event) => {
let data;
try {
data = JSON.parse(event.data);
logger.log("Server message received:", data);
} catch (e) {
logger.log("Invalid server message", event.data);
return;
}
this.emit(SocketEventType.Message, data);
};
this._socket.onclose = (event) => {
if (this._disconnected) {
return;
}
logger.log("Socket closed.", event);
this._cleanup();
this._disconnected = true;
this.emit(SocketEventType.Disconnected);
};
// Take care of the queue of connections if necessary and make sure Peer knows
// socket is open.
this._socket.onopen = () => {
if (this._disconnected) {
return;
}
this._sendQueuedMessages();
logger.log("Socket open");
this._scheduleHeartbeat();
};
}
private _scheduleHeartbeat(): void {
this._wsPingTimer = setTimeout(() => {
this._sendHeartbeat();
}, this.pingInterval);
}
private _sendHeartbeat(): void {
if (!this._wsOpen()) {
logger.log(`Cannot send heartbeat, because socket closed`);
return;
}
const message = JSON.stringify({ type: ServerMessageType.Heartbeat });
this._socket!.send(message);
this._scheduleHeartbeat();
}
/** Is the websocket currently open? */
private _wsOpen(): boolean {
return !!this._socket && this._socket.readyState === 1;
}
/** Send queued messages. */
private _sendQueuedMessages(): void {
//Create copy of queue and clear it,
//because send method push the message back to queue if smth will go wrong
const copiedQueue = [...this._messagesQueue];
this._messagesQueue = [];
for (const message of copiedQueue) {
this.send(message);
}
}
/** Exposed send for DC & Peer. */
send(data: any): void {
if (this._disconnected) {
return;
}
// If we didn't get an ID yet, we can't yet send anything so we should queue
// up these messages.
if (!this._id) {
this._messagesQueue.push(data);
return;
}
if (!data.type) {
this.emit(SocketEventType.Error, "Invalid message");
return;
}
if (!this._wsOpen()) {
return;
}
const message = JSON.stringify(data);
this._socket!.send(message);
}
close(): void {
if (this._disconnected) {
return;
}
this._cleanup();
this._disconnected = true;
}
private _cleanup(): void {
if (this._socket) {
this._socket.onopen =
this._socket.onmessage =
this._socket.onclose =
null;
this._socket.close();
this._socket = undefined;
}
clearTimeout(this._wsPingTimer!);
}
}