diff --git a/src/peer.ts b/src/peer.ts index b27c0e8..5039ff7 100644 --- a/src/peer.ts +++ b/src/peer.ts @@ -42,6 +42,8 @@ export default class Peer { private _onclose: OnClose; private _emulateWebsocket: boolean; + private _channel?: any; + constructor({ proxy, peer, @@ -55,10 +57,10 @@ export default class Peer { this._proxy = proxy; this._peer = peer; this._muxer = muxer; - this._onopen = onopen; - this._onreceive = onreceive; - this._onsend = onsend; - this._onclose = onclose; + this._onopen = onopen?.bind(this); + this._onreceive = onreceive?.bind(this); + this._onsend = onsend?.bind(this); + this._onclose = onclose?.bind(this); this._emulateWebsocket = emulateWebsocket; } @@ -69,7 +71,7 @@ export default class Peer { cb(); }; const self = this; - const channel = this._muxer.createChannel({ + this._channel = this._muxer.createChannel({ protocol: this._proxy.protocol, async onopen(m: any) { if (!m) { @@ -86,7 +88,7 @@ export default class Peer { write, emulateWebsocket: self._emulateWebsocket, }); - self._socket.on("end", () => channel.close()); + self._socket.on("end", () => this._channel.close()); let ret = await self._onopen?.(self._socket, m); if (!ret || (ret && ret.connect === false)) { // @ts-ignore @@ -100,7 +102,7 @@ export default class Peer { await self._onclose?.(self._socket); }, }); - const pipe = channel.addMessage({ + const pipe = this._channel.addMessage({ async onmessage(m: any) { if (m instanceof Uint8Array) { m = Buffer.from(m); @@ -110,6 +112,6 @@ export default class Peer { }, }); - await channel.open(); + await this._channel.open(); } }