-
Notifications
You must be signed in to change notification settings - Fork 355
/
websocket.js
268 lines (236 loc) · 5.81 KB
/
websocket.js
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
const Transport = require("../transport");
const parser = require("engine.io-parser");
const parseqs = require("parseqs");
const yeast = require("yeast");
const { pick } = require("../util");
const {
WebSocket,
usingBrowserWebSocket,
defaultBinaryType
} = require("./websocket-constructor");
const debug = require("debug")("engine.io-client:websocket");
// detect ReactNative environment
const isReactNative =
typeof navigator !== "undefined" &&
typeof navigator.product === "string" &&
navigator.product.toLowerCase() === "reactnative";
class WS extends Transport {
/**
* WebSocket transport constructor.
*
* @api {Object} connection options
* @api public
*/
constructor(opts) {
super(opts);
this.supportsBinary = !opts.forceBase64;
}
/**
* Transport name.
*
* @api public
*/
get name() {
return "websocket";
}
/**
* Opens socket.
*
* @api private
*/
doOpen() {
if (!this.check()) {
// let probe timeout
return;
}
const uri = this.uri();
const protocols = this.opts.protocols;
// React Native only supports the 'headers' option, and will print a warning if anything else is passed
const opts = isReactNative
? {}
: pick(
this.opts,
"agent",
"perMessageDeflate",
"pfx",
"key",
"passphrase",
"cert",
"ca",
"ciphers",
"rejectUnauthorized",
"localAddress",
"protocolVersion",
"origin",
"maxPayload",
"family",
"checkServerIdentity"
);
if (this.opts.extraHeaders) {
opts.headers = this.opts.extraHeaders;
}
try {
this.ws =
usingBrowserWebSocket && !isReactNative
? protocols
? new WebSocket(uri, protocols)
: new WebSocket(uri)
: new WebSocket(uri, protocols, opts);
} catch (err) {
return this.emit("error", err);
}
this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
this.addEventListeners();
}
/**
* Adds event listeners to the socket
*
* @api private
*/
addEventListeners() {
const self = this;
this.ws.onopen = function() {
self.onOpen();
};
this.ws.onclose = function() {
self.onClose();
};
this.ws.onmessage = function(ev) {
self.onData(ev.data);
};
this.ws.onerror = function(e) {
self.onError("websocket error", e);
};
}
/**
* Writes data to socket.
*
* @param {Array} array of packets.
* @api private
*/
write(packets) {
const self = this;
this.writable = false;
// encodePacket efficient as it uses WS framing
// no need for encodePayload
let total = packets.length;
let i = 0;
const l = total;
for (; i < l; i++) {
(function(packet) {
parser.encodePacket(packet, self.supportsBinary, function(data) {
// always create a new object (GH-437)
const opts = {};
if (!usingBrowserWebSocket) {
if (packet.options) {
opts.compress = packet.options.compress;
}
if (self.opts.perMessageDeflate) {
const len =
"string" === typeof data
? Buffer.byteLength(data)
: data.length;
if (len < self.opts.perMessageDeflate.threshold) {
opts.compress = false;
}
}
}
// Sometimes the websocket has already been closed but the browser didn't
// have a chance of informing us about it yet, in that case send will
// throw an error
try {
if (usingBrowserWebSocket) {
// TypeError is thrown when passing the second argument on Safari
self.ws.send(data);
} else {
self.ws.send(data, opts);
}
} catch (e) {
debug("websocket closed before onclose event");
}
--total || done();
});
})(packets[i]);
}
function done() {
self.emit("flush");
// fake drain
// defer to next tick to allow Socket to clear writeBuffer
setTimeout(function() {
self.writable = true;
self.emit("drain");
}, 0);
}
}
/**
* Called upon close
*
* @api private
*/
onClose() {
Transport.prototype.onClose.call(this);
}
/**
* Closes socket.
*
* @api private
*/
doClose() {
if (typeof this.ws !== "undefined") {
this.ws.close();
}
}
/**
* Generates uri for connection.
*
* @api private
*/
uri() {
let query = this.query || {};
const schema = this.opts.secure ? "wss" : "ws";
let port = "";
// avoid port if default for schema
if (
this.opts.port &&
(("wss" === schema && Number(this.opts.port) !== 443) ||
("ws" === schema && Number(this.opts.port) !== 80))
) {
port = ":" + this.opts.port;
}
// append timestamp to URI
if (this.opts.timestampRequests) {
query[this.opts.timestampParam] = yeast();
}
// communicate binary support capabilities
if (!this.supportsBinary) {
query.b64 = 1;
}
query = parseqs.encode(query);
// prepend ? to query
if (query.length) {
query = "?" + query;
}
const ipv6 = this.opts.hostname.indexOf(":") !== -1;
return (
schema +
"://" +
(ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) +
port +
this.opts.path +
query
);
}
/**
* Feature detection for WebSocket.
*
* @return {Boolean} whether this transport is available.
* @api public
*/
check() {
return (
!!WebSocket &&
!("__initialize" in WebSocket && this.name === WS.prototype.name)
);
}
}
module.exports = WS;