-
Notifications
You must be signed in to change notification settings - Fork 102
/
Connection.ts
42 lines (32 loc) · 1.18 KB
/
Connection.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
import WebSocketClient from '@gamestdio/websocket';
import * as msgpack from './msgpack';
export class Connection extends WebSocketClient {
private _enqueuedCalls: any[] = [];
constructor(url: string, autoConnect: boolean = true) {
super(url, undefined, { connect: autoConnect });
}
public onOpenCallback(event) {
super.onOpenCallback();
this.binaryType = 'arraybuffer';
if (this._enqueuedCalls.length > 0) {
for (const [method, args] of this._enqueuedCalls) {
this[method].apply(this, args);
}
// clear enqueued calls.
this._enqueuedCalls = [];
}
}
public send(data: ArrayBuffer | Array<number>): void {
if (this.ws.readyState === WebSocketClient.OPEN) {
if (data instanceof ArrayBuffer) {
return super.send(data);
} else if (Array.isArray(data)) {
return super.send((new Uint8Array(data)).buffer);
}
} else {
// WebSocket not connected.
// Enqueue data to be sent when readyState == OPEN
this._enqueuedCalls.push(['send', [data]]);
}
}
}