*Store channel as a private property
*Bind all callbacks to the current peer
This commit is contained in:
parent
1d4cb917c5
commit
4220037402
18
src/peer.ts
18
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();
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue