net#createServer TypeScript Examples

The following examples show how to use net#createServer. 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: portFinder.ts    From Assistive-Webdriver with MIT License 7 votes vote down vote up
/**
 * Returns a free TCP port on the local IP address specified by the host parameter.
 *
 * @param host - Specifies the local host name or IP address to use when looking for a free TCP port.
 * @returns An unused port number chosen by the operating system.
 *
 * @remarks
 *
 * This function internally creates a TCP server with port 0 so that,
 * as mentioned in the {@link https://nodejs.org/dist/latest-v15.x/docs/api/net.html#net_server_listen_port_host_backlog_callback | node.js documentation},
 * the operating system can assign an arbitrary unused port.
 * The function then closes the server and returns the port number.
 * @public
 */
export async function getFreePort({ host }: { host: string }): Promise<number> {
  const server = createServer();
  await new Promise<void>((resolve, reject) =>
    server.listen(0, host, resolve).on("error", reject)
  );
  const address = server.address() as AddressInfo;
  const port = address.port;
  await new Promise(resolve => server.close(resolve));
  return port;
}
Example #2
Source File: server.ts    From cloudmusic-vscode with MIT License 7 votes vote down vote up
static async init(): Promise<void> {
    await rm(ipcBroadcastServerPath, { recursive: true, force: true }).catch(
      () => undefined
    );

    this._server = createServer((socket) => {
      this._sockets.add(socket);

      socket
        .setEncoding("utf8")
        .on("data", (data) => this._broadcast(data))
        .on("close", (/* err */) => {
          socket?.destroy();
          this._sockets.delete(socket);
        })
        .on("error", logError);
    })
      .on("error", logError)
      .listen(ipcBroadcastServerPath);
  }
Example #3
Source File: app.ts    From ssmgr-trojan-client with MIT License 6 votes vote down vote up
server = createServer((socket: Socket) => {
  const receive: ReceiveData = {
    data: Buffer.from(''),
    socket,
  }
  socket.on('data', (data: Buffer) => {
    receive.data = Buffer.concat([receive.data, data])
    checkData(receive)
  })
  socket.on('error', (err: Error) => {
    logger.error('Socket error: ', err.message)
  })
}).on('error', (err: Error) => {
  logger.error('Socket error: ', err.message)
})
Example #4
Source File: utils.ts    From cli with MIT License 6 votes vote down vote up
checkPort = async (port): Promise<boolean> => {
  return new Promise(resolve => {
    const plat = platform();
    if (plat !== 'win32') {
      try {
        const portUse = execSync(`lsof -i:${port}`)
          .toString()
          .replace(/\n$/, '')
          .split('\n');
        if (portUse.length <= 1) {
          return resolve(false);
        }
        portUse.shift();
        const findUse = portUse.find(proc => {
          const procList = proc.split(/\s+/);
          const last = procList.pop();
          if (last === '(LISTEN)') {
            return true;
          }
        });
        if (findUse) {
          return resolve(true);
        }
      } catch {
        // ignore
      }
    }

    const server = createServer(socket => {
      socket.write('check port\r\n');
      socket.pipe(socket);
    });
    setTimeout(() => {
      server.listen(port, '127.0.0.1');
    }, 100);
    server.on('error', () => {
      resolve(true);
    });
    server.on('listening', () => {
      server.close();
      resolve(false);
    });
  });
}
Example #5
Source File: index.ts    From Adachi-BOT with MIT License 5 votes vote down vote up
private createConsole( port: number, tcp: number ) {
		this.app.use( express.static( resolve( __dirname, ".." ) ) );
		this.app.use( bodyParser.json() );
		this.app.use( bodyParser.urlencoded( { extended: false } ) );
		
		/* 创建接口 */
		this.useApi( "/check", CheckRouter, false );
		this.useApi( "/api/login", LoginRouter, false );
		this.useApi( "/api/log", LogRouter );
		this.useApi( "/api/user", UserRouter );
		this.useApi( "/api/stat", StatRouter );
		
		/* 捕获错误 */
		this.app.use( WebConsole.ApiErrorCatch );
		
		useWebsocket( this.app );
		createServer( socket => {
			let messageCache: string = "";
			socket.setEncoding( "utf-8" );
			socket.on( "data", res => {
				messageCache += res;
			} );
			
			// @ts-ignore
			this.app.ws( "/ws/log", ( ws, req ) => {
				messageCache = "";
				const cron: string = "*/2 * * * * ?";
				const job = scheduleJob( cron, () => {
					if ( messageCache.length !== 0 ) {
						ws.send( messageCache );
						messageCache = "";
					}
				} );
				ws.on( "close", () => job.cancel() && ws.close() );
			} );
			if ( this.isFirstListen ) {
				this.isFirstListen = false;
				this.app.listen( port );
			}
		} ).listen( tcp );
	}
Example #6
Source File: listener.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
/**
   * @param onClose called once listener is closed
   * @param onListening called once listener is listening
   * @param dialDirectly utility to establish a direct connection
   * @param upgradeInbound forward inbound connections to libp2p
   * @param peerId own id
   * @param options connection Options, e.g. AbortSignal
   * @param testingOptions turn on / off modules for testing
   * @param filter allow Listener to populate address filter
   * @param relay allow Listener to populate list of utilized relays
   * @param libp2p libp2p instance for various purposes
   */
  constructor(
    private onClose: () => void,
    private onListening: () => void,
    dialDirectly: HoprConnect['dialDirectly'],
    private upgradeInbound: Upgrader['upgradeInbound'],
    private peerId: PeerId,
    private options: HoprConnectOptions,
    private testingOptions: HoprConnectTestingOptions,
    private filter: Filter,
    private relay: Relay,
    libp2p: Libp2p
  ) {
    super()

    this.__connections = []

    this.tcpSocket = createServer()
    this.udpSocket = createSocket({
      // @TODO
      // `udp6` does not seem to work in Node 12.x
      // can receive IPv6 packet and IPv4 after reconnecting the socket
      type: 'udp4',
      // set to true to reuse port that is bound
      // to TCP socket
      reuseAddr: true
    })

    this.state = State.UNINITIALIZED

    this.addrs = {
      interface: [],
      external: []
    }

    this._emitListening = function (this: Listener) {
      // hopr-connect does not enable IPv6 connections right now, therefore we can set `listeningAddrs` statically
      // to `/ip4/0.0.0.0/tcp/0`, meaning listening on IPv4 using a canonical port
      // TODO check IPv6
      this.filter.setAddrs(this.getAddrs(), [new Multiaddr(`/ip4/0.0.0.0/tcp/0/p2p/${this.peerId.toB58String()}`)])

      const usedRelays = this.entry.getUsedRelayAddresses()

      if (usedRelays && usedRelays.length > 0) {
        const relayPeerIds = this.entry.getUsedRelayAddresses().map((ma: Multiaddr) => {
          const tuples = ma.tuples()

          return PeerId.createFromBytes((tuples[0][1] as Uint8Array).slice(1))
        })

        this.relay.setUsedRelays(relayPeerIds)
      }

      this.emit('listening')
    }.bind(this)

    this.entry = new EntryNodes(this.peerId, libp2p, dialDirectly, this.options)

    this.upnpManager = new UpnpManager()
  }
Example #7
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);
  });
}
Example #8
Source File: gdb-tcp-server.ts    From rp2040js with MIT License 5 votes vote down vote up
private socketServer = createServer();
Example #9
Source File: server.ts    From cloudmusic-vscode with MIT License 4 votes vote down vote up
static async init() {
    const [buf] = await Promise.allSettled([
      readFile(RETAIN_FILE),
      rm(ipcServerPath, { recursive: true, force: true }),
    ]);
    if (buf.status === "fulfilled")
      this._retain = JSON.parse(buf.value.toString()) as unknown[];

    this._server = createServer((socket) => {
      if (this._timer) {
        clearTimeout(this._timer);
        this._timer = undefined;
      }
      this._sockets.add(socket);
      this._buffer.set(socket, "");

      socket
        .setEncoding("utf8")
        .on("data", (data) => {
          const buffer = (this._buffer.get(socket) ?? "") + data.toString();

          const msgs = buffer.split(ipcDelimiter);
          this._buffer.set(socket, msgs.pop() ?? "");
          for (const msg of msgs)
            this._handler(
              JSON.parse(msg) as IPCClientMsg | NeteaseAPICMsg<"album">,
              socket
            );
        })
        .on("close", (/* err */) => {
          let isMaster = false;
          {
            const [master] = this._sockets;
            isMaster = master === socket;
          }
          socket?.destroy();
          this._sockets.delete(socket);
          this._buffer.delete(socket);

          if (this._sockets.size) {
            this._setMaster();
            if (isMaster) {
              // Master was gone, the wasm player was destroyed
              // So we need to recreate it on new master
              Player.wasmOpen();
            }
          } else {
            Player.pause();
            this._timer = setTimeout(() => {
              if (this._sockets.size) return;
              this.stop();
              IPCBroadcastServer.stop();
              Promise.allSettled([
                MusicCache.store(),
                rm(TMP_DIR, { recursive: true }),
                writeFile(RETAIN_FILE, JSON.stringify(this._retain)),
              ]).finally(() => process.exit());
            }, 20000);
          }
        })
        .on("error", logError);

      this._setMaster();

      if (this._sockets.size === 1) {
        // retain
        if (!this._first) {
          Player.play();

          this.send(socket, { t: IPCControl.retain, items: this._retain });
          this._retain = [];
        } else this._first = false;
      } else {
        this.sendToMaster({ t: IPCControl.new });
        this.send(socket, {
          t: Player.playing ? IPCPlayer.play : IPCPlayer.pause,
        });
      }
    })
      .on("error", logError)
      .listen(ipcServerPath);
  }
Example #10
Source File: tcp.spec.ts    From hoprnet with GNU General Public License v3.0 4 votes vote down vote up
describe('test TCP connection', function () {
  it('should test TCPConnection against Node.js APIs', async function () {
    const msgReceived = defer<void>()

    const testMessage = new TextEncoder().encode('test')
    const testMessageReply = new TextEncoder().encode('reply')

    const peerId = createPeerId()

    const server = createServer((socket: Socket) => {
      socket.on('data', (data: Uint8Array) => {
        assert(u8aEquals(data, testMessage))
        socket.write(testMessageReply)

        msgReceived.resolve()
      })
    })

    await waitUntilListening<undefined | number>(server, undefined)

    const conn = await TCPConnection.create(
      new Multiaddr(`/ip4/127.0.0.1/tcp/${(server.address() as AddressInfo).port}`),
      peerId
    )

    await conn.sink(
      (async function* () {
        yield testMessage
      })()
    )

    for await (const msg of conn.source) {
      assert(u8aEquals(msg.slice(), testMessageReply))
    }

    await msgReceived.promise

    conn.close()

    await once(conn.conn as EventEmitter, 'close')

    assert(conn.conn.destroyed)

    assert(
      conn.timeline.close != undefined &&
        conn.timeline.close <= Date.now() &&
        conn.timeline.open <= conn.timeline.close,
      `TCPConnection must populate timeline object`
    )

    await stopNode(server)
  })

  it('trigger a socket close timeout', async function () {
    this.timeout(SOCKET_CLOSE_TIMEOUT + 2e3)

    const testMessage = new TextEncoder().encode('test')

    const server = createServer()

    server.on('close', console.log)
    server.on('error', console.log)
    const sockets: Socket[] = []
    server.on('connection', sockets.push.bind(sockets))

    await waitUntilListening(server, undefined)

    const peerId = createPeerId()
    const conn = await TCPConnection.create(
      new Multiaddr(`/ip4/127.0.0.1/tcp/${(server.address() as AddressInfo).port}`),
      peerId
    )

    await conn.sink(
      (async function* () {
        yield testMessage
      })()
    )

    const start = Date.now()
    const closePromise = once(conn.conn, 'close')

    // Overwrite end method to mimic half-open stream
    Object.assign(conn.conn, {
      end: () => {}
    })

    // @dev produces a half-open socket on the other side
    conn.close()

    await closePromise

    // Destroy half-open sockets.
    for (const socket of sockets) {
      socket.destroy()
    }

    await stopNode(server)

    assert(Date.now() - start >= SOCKET_CLOSE_TIMEOUT)

    assert(
      conn.timeline.close != undefined &&
        conn.timeline.close <= Date.now() &&
        conn.timeline.open <= conn.timeline.close,
      `TCPConnection must populate timeline object`
    )
  })

  it('tcp socket timeout and error cases', async function () {
    const INVALID_PORT = 54221
    const peerId = createPeerId()

    await assert.rejects(
      async () => {
        await TCPConnection.create(new Multiaddr(`/ip4/127.0.0.1/tcp/${INVALID_PORT}`), peerId)
      },
      {
        name: 'Error',
        code: 'ECONNREFUSED'
      }
    )
  })

  it('use abortController to abort streams', async function () {
    const msgReceived = defer<void>()

    const testMessage = new TextEncoder().encode('test')
    const testMessageReply = new TextEncoder().encode('reply')

    const peerId = createPeerId()

    const server = createServer((socket: Socket) => {
      socket.on('data', (data: Uint8Array) => {
        assert(u8aEquals(data, testMessage))
        socket.write(testMessageReply)

        msgReceived.resolve()
      })
    })

    await waitUntilListening<undefined | number>(server, undefined)

    const abort = new AbortController()

    const conn = await TCPConnection.create(
      new Multiaddr(`/ip4/127.0.0.1/tcp/${(server.address() as AddressInfo).port}`),
      peerId,
      {
        signal: abort.signal
      }
    )

    await assert.doesNotReject(
      async () =>
        await conn.sink(
          (async function* () {
            abort.abort()
            yield testMessage
          })()
        )
    )

    await stopNode(server)
  })
})