* Sets the current transport `socket`. * * @param {Function} fn - optional, callback * @return self * @public
(fn?: (err?: Error) => void)
| 316 | * @public |
| 317 | */ |
| 318 | public open(fn?: (err?: Error) => void): this { |
| 319 | debug(class="st">"readyState %s", this._readyState); |
| 320 | if (~this._readyState.indexOf(class="st">"open")) return this; |
| 321 | |
| 322 | debug(class="st">"opening %s", this.uri); |
| 323 | this.engine = new Engine(this.uri, this.opts); |
| 324 | const socket = this.engine; |
| 325 | const self = this; |
| 326 | this._readyState = class="st">"opening"; |
| 327 | this.skipReconnect = false; |
| 328 | |
| 329 | class="cm">// emit `open` |
| 330 | const openSubDestroy = on(socket, class="st">"open", function () { |
| 331 | self.onopen(); |
| 332 | fn && fn(); |
| 333 | }); |
| 334 | |
| 335 | const onError = (err) => { |
| 336 | debug(class="st">"error"); |
| 337 | this.cleanup(); |
| 338 | this._readyState = class="st">"closed"; |
| 339 | this.emitReserved(class="st">"error", err); |
| 340 | if (fn) { |
| 341 | fn(err); |
| 342 | } else { |
| 343 | class="cm">// Only do this if there is no fn to handle the error |
| 344 | this.maybeReconnectOnOpen(); |
| 345 | } |
| 346 | }; |
| 347 | |
| 348 | class="cm">// emit `error` |
| 349 | const errorSub = on(socket, class="st">"error", onError); |
| 350 | |
| 351 | if (false !== this._timeout) { |
| 352 | const timeout = this._timeout; |
| 353 | debug(class="st">"connect attempt will timeout after %d", timeout); |
| 354 | |
| 355 | class="cm">// set timer |
| 356 | const timer = this.setTimeoutFn(() => { |
| 357 | debug(class="st">"connect attempt timed out after %d", timeout); |
| 358 | openSubDestroy(); |
| 359 | onError(new Error(class="st">"timeout")); |
| 360 | socket.close(); |
| 361 | }, timeout); |
| 362 | |
| 363 | if (this.opts.autoUnref) { |
| 364 | timer.unref(); |
| 365 | } |
| 366 | |
| 367 | this.subs.push(() => { |
| 368 | this.clearTimeoutFn(timer); |
| 369 | }); |
| 370 | } |
| 371 | |
| 372 | this.subs.push(openSubDestroy); |
| 373 | this.subs.push(errorSub); |
| 374 | |
| 375 | return this; |