net#connect TypeScript Examples

The following examples show how to use net#connect. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: impl.ts    From kassette with MIT License 6 votes vote down vote up
process(): void {
    if (this._processed) {
      return;
    }
    this._processed = true;
    const socket = this.socket;
    if (this.mode === 'close') {
      this.socket.end();
    } else if (this.mode === 'intercept') {
      pushSocketConnection(socket, this.hostname, this.port, '');
      this._intercept(socket);
      socket.write('HTTP/1.1 200 Connection established\r\n\r\n');
    } else if (this.mode === 'forward') {
      const remoteSocket = connect(this.destinationPort, this.destinationHostname, () => {
        socket.write('HTTP/1.1 200 Connection established\r\n\r\n');
        remoteSocket.pipe(socket);
        socket.pipe(remoteSocket);
      }).on('error', () => {
        socket.end('HTTP/1.1 500 Connection error\r\n\r\n');
      });
    }
  }
Example #2
Source File: ipc.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
connect(handler: (data: U) => void, retry: number): Promise<boolean> {
    if (this._socket?.readable && this._socket.writable)
      return Promise.resolve(true);
    else this.disconnect();
    return new Promise(
      (resolve) =>
        void this._tryConnect(retry)
          .then((socket) => {
            if (!socket) throw new Error();

            this._socket = socket
              .on("data", (data) => {
                const buffer = this._buffer + data.toString();

                const msgs = buffer.split(ipcDelimiter);
                this._buffer = msgs.pop() ?? "";
                for (const msg of msgs) handler(JSON.parse(msg) as U);
              })
              .on("close", () => this.disconnect())
              .on("error", console.error);

            resolve(true);
          })
          .catch(() => resolve(false))
    );
  }
Example #3
Source File: ipc.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
private _tryConnect(retry: number): Promise<Socket | undefined> {
    return new Promise((resolve) => {
      const setTimer = (remain: number) => {
        const socket = connect({ path: this._path }).setEncoding("utf8");
        const listener = () => {
          socket.destroy();
          if (remain > 0) setTimeout(() => setTimer(remain - 1), 512);
          else resolve(undefined);
        };
        socket
          .on("error", ({ message }) => console.error(message))
          .once("connect", () => {
            setTimeout(() => resolve(socket), 512);
            socket.off("close", listener);
          })
          .once("close", listener);
      };
      if (retry <= 0) setTimer(0);
      else setTimeout(() => setTimer(retry), 512);
    });
  }
Example #4
Source File: ipc.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
static connect(
    ipcHandler: Parameters<typeof ipc.connect>[0],
    ipcBHandler: Parameters<typeof ipcB.connect>[0],
    retry = 4
  ): Promise<[boolean, boolean]> {
    return Promise.all([
      ipc.connect(ipcHandler, retry),
      ipcB.connect(ipcBHandler, retry),
    ]);
  }
Example #5
Source File: tcp.ts    From mtcute with GNU Lesser General Public License v3.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
    connect(dc: tl.RawDcOption, testMode: boolean): void {
        if (this._state !== TransportState.Idle)
            throw new Error('Transport is not IDLE')

        if (!this.packetCodecInitialized) {
            this._packetCodec.setup?.(this._crypto, this.log)
            this._packetCodec.on('error', (err) => this.emit('error', err))
            this._packetCodec.on('packet', (buf) => this.emit('message', buf))
            this.packetCodecInitialized = true
        }

        this._state = TransportState.Connecting
        this._currentDc = dc
        this._updateLogPrefix()

        this.log.debug('connecting to %j', dc)

        this._socket = connect(
            dc.port,
            dc.ipAddress,
            this.handleConnect.bind(this)
        )

        this._socket.on('data', (data) => this._packetCodec.feed(data))
        this._socket.on('error', this.handleError.bind(this))
        this._socket.on('close', this.close.bind(this))
    }
Example #6
Source File: index.ts    From mtcute with GNU Lesser General Public License v3.0 6 votes vote down vote up
connect(dc: tl.RawDcOption): void {
        if (this._state !== TransportState.Idle)
            throw new Error('Transport is not IDLE')

        if (!this.packetCodecInitialized) {
            this._packetCodec.on('error', (err) => this.emit('error', err))
            this._packetCodec.on('packet', (buf) => this.emit('message', buf))
            this.packetCodecInitialized = true
        }

        this._state = TransportState.Connecting
        this._currentDc = dc

        this._socket = connect(
            this._proxy.port,
            this._proxy.host,
            this._onProxyConnected.bind(this)
        )

        this._socket.on('error', this.handleError.bind(this))
        this._socket.on('close', this.close.bind(this))
    }
Example #7
Source File: index.ts    From mtcute with GNU Lesser General Public License v3.0 5 votes vote down vote up
connect(dc: tl.RawDcOption, testMode: boolean): void {
        if (this._state !== TransportState.Idle)
            throw new Error('Transport is not IDLE')

        if (this._packetCodec && this._currentDc?.id !== dc.id) {
            // dc changed, thus the codec's init will change too
            // clean up to avoid memory leaks
            this.packetCodecInitialized = false
            this._packetCodec.reset()
            this._packetCodec.removeAllListeners()
            delete (this as any)._packetCodec
        }

        if (!this._packetCodec) {
            const proxy = {
                dcId: dc.id,
                media: dc.mediaOnly!,
                test: testMode,
                secret: this._rawSecret,
            }

            if (!this._fakeTlsDomain) {
                let inner: IPacketCodec
                if (this._randomPadding) {
                    inner = new PaddedIntermediatePacketCodec()
                } else {
                    inner = new IntermediatePacketCodec()
                }

                this._packetCodec = new ObfuscatedPacketCodec(inner, proxy)
            } else {
                this._packetCodec = new FakeTlsPacketCodec(
                    new ObfuscatedPacketCodec(
                        new PaddedIntermediatePacketCodec(),
                        proxy
                    )
                )
            }

            this._packetCodec.setup?.(this._crypto, this.log)
            this._packetCodec.on('error', (err) => this.emit('error', err))
            this._packetCodec.on('packet', (buf) => this.emit('message', buf))
        }

        this._state = TransportState.Connecting
        this._currentDc = dc

        if (this._fakeTlsDomain) {
            this._socket = connect(
                this._proxy.port,
                this._proxy.host,
                this._handleConnectFakeTls.bind(this)
            )
        } else {
            this._socket = connect(
                this._proxy.port,
                this._proxy.host,
                this.handleConnect.bind(this)
            )
            this._socket.on('data', (data) => this._packetCodec.feed(data))
        }
        this._socket.on('error', this.handleError.bind(this))
        this._socket.on('close', this.close.bind(this))
    }
Example #8
Source File: proxy.ts    From l2js-client with MIT License 5 votes vote down vote up
proxy = (cfg: ProxyConfig) => {
  const server = createServer(client => {
    const connectOption: NetConnectOpts = {
      port: cfg.remotePort,
      host: cfg.remoteIp
    };
    // Proxy client
    const remote: Socket = connect(connectOption);

    client.on("end", () => remote.destroy());

    client.on("error", () => remote.destroy());

    client.on("data", (data: Uint8Array) => {
      client.pause();
      remote.write(data);
      client.resume();
    });

    remote.on("data", (data: Uint8Array) => {
      remote.pause();

      cfg.mmoClient
        .process(data)
        .then((packet: ReceivablePacket) => {
          if (packet != null && packet instanceof ServerList) {
            const list = (cfg.mmoClient as LoginClient).Servers;
            const fakeServerListPacket = new (class extends SendablePacket {
              write(): void {
                this.writeC(0x04);
                this.writeC(list.length);
                this.writeC(1);
                list.forEach(s => {
                  this.writeC(s.Id);
                  this.writeD(0x0100007f); // 127.0.0.1
                  this.writeD(s.Port);
                  this.writeC(s.AgeLimit);
                  this.writeC(s.Pvp);
                  this.writeH(s.CurrentPlayers);
                  this.writeH(s.MaxPlayers);
                  this.writeC(s.Status);
                  this.writeD(s.ServerType);
                  this.writeC(s.Brackets);
                });
                this.writeH(0);
                this.writeC(0);
              }
            })();
            // fakeServerListPacket.Client = cfg.mmoClient as LoginClient;

            data = cfg.mmoClient.pack(fakeServerListPacket);
          }

          client.write(data);
          remote.resume();
        })
        .catch(() => {
          client.write(data);
          remote.resume();
        });
    });

    remote.on("end", () => client.destroy());
    remote.on("error", () => client.destroy());
  });

  server.listen(cfg.listenPort, () => {
    console.info("Listen on port:", cfg.listenPort);
  });
}