net#Socket TypeScript Examples

The following examples show how to use net#Socket. 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: utils.ts    From big-web-quiz with Apache License 2.0 7 votes vote down vote up
export function abortHandshake(
  socket: Socket,
  code: number,
  message: string = STATUS_CODES[code] || 'unknown',
  headers: { [headerName: string]: string } = {},
) {
  if (socket.writable) {
    headers = {
      Connection: 'close',
      'Content-type': 'text/html',
      'Content-Length': Buffer.byteLength(message).toString(),
      ...headers,
    };

    socket.write(
      `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` +
        Object.keys(headers)
          .map(h => `${h}: ${headers[h]}`)
          .join('\r\n') +
        '\r\n\r\n' +
        message,
    );
  }

  socket.destroy();
}
Example #2
Source File: remote-procedures-server.ts    From leapp with Mozilla Public License 2.0 6 votes vote down vote up
private refreshIntegrations(emitFunction: EmitFunction, socket: Socket): void {
    try {
      this.repository.reloadWorkspace();
      this.uiSafeFn(() => {
        const workspace = this.repository.getWorkspace();
        workspace.awsSsoIntegrations = this.repository.listAwsSsoIntegrations();
        this.repository.persistWorkspace(workspace);
        this.behaviouralSubjectService.setIntegrations(this.repository.listAwsSsoIntegrations());
      });
      emitFunction(socket, "message", {});
    } catch (error) {
      emitFunction(socket, "message", { error: error.message });
    }
  }
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: remote-procedures-server.ts    From leapp with Mozilla Public License 2.0 6 votes vote down vote up
private needMfa(emitFunction: EmitFunction, socket: Socket, data: RpcRequest): void {
    try {
      this.mfaCodePrompter.promptForMFACode(data.params.sessionName, (result) => {
        emitFunction(socket, "message", { result });
      });
    } catch (error) {
      emitFunction(socket, "message", { error: error.message });
    }
  }
Example #5
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 #6
Source File: index.tsx    From big-web-quiz with Apache License 2.0 6 votes vote down vote up
export function upgrade(req: Request, socket: Socket, head: Buffer) {
  if (requirePlayerLogin && !req.session!.user) {
    abortHandshake(socket, 403);
    return;
  }

  let voterId: string;

  if (req.session!.user) {
    voterId = req.session!.user.id;
  } else if (req.session!.voterId) {
    voterId = req.session!.voterId;
  } else {
    const id = uuidv4();
    voterId = id;
    req.session!.voterId = id;
  }

  wss.handleUpgrade(req, socket, head, ws => {
    wsToVoterId.set(ws, voterId);
    wss.emit('connection', ws, req);
  });
}
Example #7
Source File: server.ts    From nouns-monorepo with GNU General Public License v3.0 6 votes vote down vote up
createServer = (app: Express): Server => {
  const server = app.listen(config.serverPort, () => {
    console.info(`HTTP service listening on 0.0.0.0:${config.serverPort}`);
  });

  let connections: Socket[] = [];

  server.on('connection', (connection: Socket) => {
    connections.push(connection);
    connection.on(
      'close',
      () => (connections = connections.filter((curr: Socket) => curr !== connection)),
    );
  });

  const handles = {
    shutdown: () => {
      console.info('Received kill signal, shutting down gracefully');
      server.close(() => {
        console.info('Closed out remaining connections');
        process.exit(0);
      });

      setTimeout(() => {
        console.error('Could not close connections in time, forcefully shutting down');
        process.exit(1);
      }, 10000);

      connections.forEach((curr: Socket) => curr.end());
      setTimeout(() => connections.forEach((curr: Socket) => curr.destroy()), 5000);
    },
  };
  process.on('SIGTERM', handles.shutdown);
  process.on('SIGINT', handles.shutdown);

  return server;
}
Example #8
Source File: impl.ts    From kassette with MIT License 6 votes vote down vote up
public async process(
    socket: Socket,
    hostname = getSocketConnection(socket).hostname,
  ): Promise<Socket> {
    const secureContext = await this._getSecureContext(hostname);
    const SNICallback = async (
      sni: string,
      callback: (error: Error | null, context: SecureContext) => void,
    ) => {
      const sniContext = sni === hostname ? secureContext : await this._getSecureContext(sni);
      callback(null, sniContext);
    };
    const tlsSocket = new TLSSocket(socket, {
      isServer: true,
      SNICallback,
      secureContext,
    });
    forwardSocketConnections(socket, tlsSocket);
    return tlsSocket;
  }
Example #9
Source File: helper.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
export function broadcastProfiles(socket?: Socket): void {
  const msg: IPCServerMsg = {
    t: IPCControl.netease,
    cookies: [...AccountState.cookies].map(([uid, c]) => ({
      uid,
      cookie: JSON.stringify(c),
    })),
    profiles: [...AccountState.profile.values()],
  };
  socket ? IPCServer.send(socket, msg) : IPCServer.broadcast(msg);
}
Example #10
Source File: getIP.ts    From graphene with MIT License 6 votes vote down vote up
/**
 * @param socket - The net.Socket object associated with the request
 * @returns {boolean}
 */
function trustRemoteAddress(socket: Socket): TrustFunction {
  const addresses = socket.remoteAddress;

  if (addresses !== undefined) {
    return compile(addresses.split(",").map((x) => x.trim()));
  }

  return compile([]);
}
Example #11
Source File: index.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
function launchv2(
  opts?: {} & LaunchOpts
): Promise<{ port: number; server: Server; serverSockets: Set<Socket> }> {
  const ctx = "launch";

  const listenPort = opts?.port || 0;
  const LOG_DST = opts?.logPath ? opts.logPath : "stdout";
  configureLogger({ logPath: LOG_DST });

  return new Promise((resolve) => {
    // eslint-disable-next-line global-require
    const appModule = require("./Server").appModule;
    const app = appModule({
      logPath: LOG_DST,
      nextServerUrl: opts?.nextServerUrl,
      nextStaticRoot: opts?.nextStaticRoot,
      googleOauthClientId: opts?.googleOauthClientId,
      googleOauthClientSecret: opts?.googleOauthClientSecret,
    });

    const serverSockets = new Set<Socket>();

    const server = app.listen(listenPort, "localhost", () => {
      const port = (server.address() as any).port;
      getLogger().info({ ctx, msg: "exit", port, LOG_DST, root: __dirname });

      // delete all active sockets on server close
      server.on("connection", (socket: Socket) => {
        serverSockets.add(socket);
        socket.on("close", () => {
          serverSockets.delete(socket);
        });
      });
      resolve({ port, server, serverSockets });
    });
  });
}
Example #12
Source File: connection.ts    From kassette with MIT License 6 votes vote down vote up
pushSocketConnection = (
  socket: Socket,
  hostname: string,
  port: number,
  protocol: string,
) => {
  const socketInfo = _getSocketConnections(socket);
  socketInfo.push({ hostname, port, protocol });
}
Example #13
Source File: gdb-tcp-server.ts    From rp2040js with MIT License 6 votes vote down vote up
handleConnection(socket: Socket) {
    this.info('GDB connected');
    socket.setNoDelay(true);

    const connection = new GDBConnection(this, (data) => {
      socket.write(data);
    });

    socket.on('data', (data) => {
      connection.feedData(data.toString('utf-8'));
    });

    socket.on('error', (err) => {
      this.removeConnection(connection);
      this.error(`GDB socket error ${err}`);
    });

    socket.on('close', () => {
      this.removeConnection(connection);
      this.info('GDB disconnected');
    });
  }
Example #14
Source File: connection.ts    From kassette with MIT License 6 votes vote down vote up
_getSocketConnections = (socket: Socket) => {
  let result = socketConnectionsMap.get(socket);
  if (!result) {
    result = [
      {
        hostname: socket.localAddress!,
        port: socket.localPort!,
        protocol: 'http',
      },
    ];
    socketConnectionsMap.set(socket, result);
  }
  return result;
}
Example #15
Source File: tcp.ts    From mtcute with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected _socket: Socket | null = null
Example #16
Source File: utils.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Setup an engine based on CLI args
 */
export async function setupEngine(
  opts: SetupEngineCLIOpts
): Promise<SetupEngineResp> {
  const logger = createLogger();
  const { enginePort, init, useLocalEngine } = _.defaults(opts, {
    init: true,
    useLocalEngine: false,
  });
  let engine: DEngineClient;
  let port: number;
  let server: Server;
  let serverSockets = new Set<Socket>();
  const wsRoot = resolvePath(opts.wsRoot, process.cwd());
  const ctx = "setupEngine";

  // instead of spwaning an engine in a separate process, create one
  // in memory
  if (useLocalEngine) {
    const engine = DendronEngineV2.create({ wsRoot, logger });
    const out = await engine.init();
    if (out.error) {
      // eslint-disable-next-line no-console
      console.error(out.error);
    }
    return {
      wsRoot,
      engine,
      port: -1,
      server: createDummyServer(),
      serverSockets: new Set(),
    };
  }

  // connect to a running engine at specified port
  if (enginePort) {
    logger.info({
      ctx,
      msg: "connecting to engine at port",
      enginePort,
      init,
    });
    const engineConnector = EngineConnector.getOrCreate({
      wsRoot,
    });
    await engineConnector.init({
      portOverride: enginePort,
      init,
    });
    engine = engineConnector.engine;
    port = enginePort;
    // the server is running somewhere else
    // we need a dummy server because the calling function
    // will try to close the server
    server = createDummyServer();
    return { wsRoot, engine, port, server, serverSockets };
  }

  if (opts.attach) {
    logger.info({
      ctx,
      msg: "connecting to running engine",
      attach: opts.attach,
      init,
    });
    const engineConnector = EngineConnector.getOrCreate({
      wsRoot,
    });
    await engineConnector.init({
      init,
      target: opts.target,
    });
    engine = engineConnector.engine;
    port = engineConnector.port!;
    if (engineConnector.serverPortWatcher) {
      // a file watcher is created when engine port is undefined
      // needs to be cleaned up on server closing
      server = createDummyServer(async () => {
        engineConnector.serverPortWatcher?.close();
      });
    } else {
      server = createDummyServer();
    }
    return { wsRoot, engine, port, server, serverSockets };
  }

  // if not using current engine, initialize a new one
  logger.info({ ctx, msg: "initialize new engine" });
  const resp = await new LaunchEngineServerCommand().enrichArgs(opts);
  ({ engine, port, server, serverSockets } = resp.data);
  if (init) {
    const out = await engine.init();
    // eslint-disable-next-line no-console
    if (out.error) console.error(out.error);
  }
  return { wsRoot, engine, port, server, serverSockets };
}
Example #17
Source File: client.ts    From companion-satellite with MIT License 5 votes vote down vote up
private socket: Socket | undefined
Example #18
Source File: inspector-util.ts    From stacks-blockchain-api with GNU General Public License v3.0 5 votes vote down vote up
export async function startProfilerServer(
  httpServerPort?: number | string
): Promise<{
  server: Server;
  address: string;
  close: () => Promise<void>;
}> {
  let serverPort: number | undefined = undefined;
  if (httpServerPort !== undefined) {
    serverPort = parsePort(httpServerPort);
  }
  const app = express();

  let existingSession:
    | { instance: ProfilerInstance<unknown>; response: express.Response }
    | undefined;

  app.get(
    '/profile/cpu',
    asyncHandler(async (req, res) => {
      if (existingSession) {
        res.status(409).json({ error: 'Profile session already in progress' });
        return;
      }
      const durationParam = req.query['duration'];
      const seconds = Number.parseFloat(durationParam as string);
      if (!Number.isFinite(seconds) || seconds < 0) {
        res.status(400).json({ error: `Invalid 'duration' query parameter "${durationParam}"` });
        return;
      }
      const samplingIntervalParam = req.query['sampling_interval'];
      let samplingInterval: number | undefined;
      if (samplingIntervalParam !== undefined) {
        samplingInterval = Number.parseFloat(samplingIntervalParam as string);
        if (!Number.isInteger(samplingInterval) || samplingInterval < 0) {
          res.status(400).json({
            error: `Invalid 'sampling_interval' query parameter "${samplingIntervalParam}"`,
          });
          return;
        }
      }
      const cpuProfiler = initCpuProfiling(samplingInterval);
      existingSession = { instance: cpuProfiler, response: res };
      try {
        const filename = `cpu_${Math.round(Date.now() / 1000)}_${seconds}-seconds.cpuprofile`;
        res.setHeader('Cache-Control', 'no-store');
        res.setHeader('Transfer-Encoding', 'chunked');
        res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.flushHeaders();
        await cpuProfiler.start();
        const ac = new AbortController();
        const timeoutPromise = timeout(seconds * 1000, ac);
        await Promise.race([timeoutPromise, once(res, 'close')]);
        if (res.writableEnded || res.destroyed) {
          // session was cancelled
          ac.abort();
          return;
        }
        const result = await cpuProfiler.stop();
        const resultString = JSON.stringify(result);
        logger.info(
          `[CpuProfiler] Completed, total profile report JSON string length: ${resultString.length}`
        );
        res.end(resultString);
      } finally {
        const session = existingSession;
        existingSession = undefined;
        await session?.instance.dispose().catch();
      }
    })
  );

  let neonProfilerRunning: boolean = false;

  app.get(
    '/profile/cpu/start',
    asyncHandler(async (req, res) => {
      if (existingSession) {
        res.status(409).json({ error: 'Profile session already in progress' });
        return;
      }
      const samplingIntervalParam = req.query['sampling_interval'];
      let samplingInterval: number | undefined;
      if (samplingIntervalParam !== undefined) {
        samplingInterval = Number.parseFloat(samplingIntervalParam as string);
        if (!Number.isInteger(samplingInterval) || samplingInterval < 0) {
          res.status(400).json({
            error: `Invalid 'sampling_interval' query parameter "${samplingIntervalParam}"`,
          });
          return;
        }
      }
      const cpuProfiler = initCpuProfiling(samplingInterval);
      existingSession = { instance: cpuProfiler, response: res };
      await cpuProfiler.start();
      const profilerRunningLogger = setInterval(() => {
        if (existingSession) {
          logger.error(`CPU profiler has been enabled for a long time`);
        } else {
          clearInterval(profilerRunningLogger);
        }
      }, 10_000).unref();
      res.end('CPU profiler started');
    })
  );

  app.get('/profile/native/cpu/start', (req, res) => {
    if (neonProfilerRunning) {
      res.status(500).end('error: profiler already started');
      return;
    }
    neonProfilerRunning = true;
    try {
      const startResponse = startProfiler();
      console.log(startResponse);
      res.end(startResponse);
    } catch (error) {
      console.error(error);
      res.status(500).end(error);
    }
  });

  app.get('/profile/native/cpu/stop', (req, res) => {
    if (!neonProfilerRunning) {
      res.status(500).end('error: no profiler running');
      return;
    }
    neonProfilerRunning = false;
    let profilerResults: Buffer;
    try {
      profilerResults = stopProfiler();
    } catch (error: any) {
      console.error(error);
      res.status(500).end(error);
      return;
    }
    const fileName = `profile-${Date.now()}.svg`;
    res.setHeader('Cache-Control', 'no-store');
    res.setHeader('Transfer-Encoding', 'chunked');
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
    res.setHeader('Content-Type', 'image/svg+xml');
    res.status(200).send(profilerResults);
  });

  app.get(
    '/profile/cpu/stop',
    asyncHandler(async (req, res) => {
      if (!existingSession) {
        res.status(409).json({ error: 'No profile session in progress' });
        return;
      }
      if (existingSession.instance.sessionType !== 'cpu') {
        res.status(409).json({ error: 'No CPU profile session in progress' });
        return;
      }
      try {
        const elapsedSeconds = existingSession.instance.stopwatch.getElapsedSeconds();
        const timestampSeconds = Math.round(Date.now() / 1000);
        const filename = `cpu_${timestampSeconds}_${elapsedSeconds}-seconds.cpuprofile`;
        const result = await (existingSession.instance as ProfilerInstance<inspector.Profiler.Profile>).stop();
        const resultString = JSON.stringify(result);
        logger.info(
          `[CpuProfiler] Completed, total profile report JSON string length: ${resultString.length}`
        );

        res.setHeader('Cache-Control', 'no-store');
        res.setHeader('Transfer-Encoding', 'chunked');
        res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        // await new Promise<void>(resolve => res.end(resultString, () => resolve()));
        res.end(resultString);
      } finally {
        const session = existingSession;
        existingSession = undefined;
        await session?.instance.dispose().catch();
      }
    })
  );

  app.get(
    '/profile/heap_snapshot',
    asyncHandler(async (req, res) => {
      if (existingSession) {
        res.status(409).json({ error: 'Profile session already in progress' });
        return;
      }
      const filename = `heap_${Math.round(Date.now() / 1000)}.heapsnapshot`;
      const tmpFile = path.join(os.tmpdir(), filename);
      const fileWriteStream = fs.createWriteStream(tmpFile);
      const heapProfiler = initHeapSnapshot(fileWriteStream);
      existingSession = { instance: heapProfiler, response: res };
      try {
        res.setHeader('Cache-Control', 'no-store');
        res.setHeader('Transfer-Encoding', 'chunked');
        res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.flushHeaders();
        // Taking a heap snapshot (with current implementation) is a one-shot process ran to get the
        // applications current heap memory usage, rather than something done over time. So start and
        // stop without waiting.
        await heapProfiler.start();
        const result = await heapProfiler.stop();
        logger.info(
          `[HeapProfiler] Completed, total snapshot byte size: ${result.totalSnapshotByteSize}`
        );
        await pipelineAsync(fs.createReadStream(tmpFile), res);
      } finally {
        const session = existingSession;
        existingSession = undefined;
        await session?.instance.dispose().catch();
        try {
          fileWriteStream.destroy();
        } catch (_) {}
        try {
          logger.info(`[HeapProfiler] Cleaning up tmp file ${tmpFile}`);
          fs.unlinkSync(tmpFile);
        } catch (_) {}
      }
    })
  );

  app.get(
    '/profile/cancel',
    asyncHandler(async (req, res) => {
      if (!existingSession) {
        res.status(409).json({ error: 'No existing profile session is exists to cancel' });
        return;
      }
      const session = existingSession;
      await session.instance.stop().catch();
      await session.instance.dispose().catch();
      session.response.destroy();
      existingSession = undefined;
      await Promise.resolve();
      res.json({ ok: 'existing profile session stopped' });
    })
  );

  const server = createServer(app);

  const serverSockets = new Set<Socket>();
  server.on('connection', socket => {
    serverSockets.add(socket);
    socket.once('close', () => {
      serverSockets.delete(socket);
    });
  });

  await new Promise<void>((resolve, reject) => {
    try {
      server.once('error', error => {
        reject(error);
      });
      server.listen(serverPort, '0.0.0.0', () => {
        resolve();
      });
    } catch (error) {
      reject(error);
    }
  });

  const addr = server.address();
  if (addr === null) {
    throw new Error('server missing address');
  }
  const addrStr = typeof addr === 'string' ? addr : `${addr.address}:${addr.port}`;
  logger.info(`Started profiler server on: http://${addrStr}`);

  const closeServer = async () => {
    const closePromise = new Promise<void>((resolve, reject) => {
      if (!server.listening) {
        // Server already closed (can happen when server is shared between cluster workers)
        return resolve();
      }
      server.close(error => (error ? reject(error) : resolve()));
    });
    for (const socket of serverSockets) {
      socket.destroy();
    }
    await closePromise;
  };

  return { server, address: addrStr, close: closeServer };
}
Example #19
Source File: client.ts    From companion-satellite with MIT License 5 votes vote down vote up
private initSocket(): void {
		const socket = (this.socket = new Socket())
		this.socket.on('error', (e) => {
			this.emit('error', e)
		})
		this.socket.on('close', () => {
			if (this.debug) {
				this.emit('log', 'Connection closed')
			}

			if (this._connected) {
				this.emit('disconnected')
			}
			this._connected = false
			this.receiveBuffer = ''

			if (this._pingInterval) {
				clearInterval(this._pingInterval)
				this._pingInterval = undefined
			}

			if (!this._retryConnectTimeout && this.socket === socket) {
				this._retryConnectTimeout = setTimeout(() => {
					this._retryConnectTimeout = undefined
					this.emit('log', 'Trying reconnect')
					this.initSocket()
				}, RECONNECT_DELAY)
			}
		})

		this.socket.on('data', (d) => this._handleReceivedData(d))

		this.socket.on('connect', () => {
			if (this.debug) {
				this.emit('log', 'Connected')
			}

			this._connected = true
			this._pingUnackedCount = 0
			this.receiveBuffer = ''

			if (!this._pingInterval) {
				this._pingInterval = setInterval(() => this.sendPing(), PING_INTERVAL)
			}

			if (!this.socket) {
				// should never hit, but just in case
				this.disconnect()
				return
			}

			this.emit('connected')
		})

		if (this._host) {
			this.emit('log', `Connecting to ${this._host}:${this._port}`)
			this.socket.connect(this._port, this._host)
		}
	}
Example #20
Source File: auto-languageclient.ts    From atom-languageclient with MIT License 5 votes vote down vote up
protected socket!: Socket
Example #21
Source File: connection-tcp.ts    From node-vmix with MIT License 5 votes vote down vote up
/**
     * Get "raw" TCP socket
     * 
     * @returns Socket | null
     */
    socket(): Socket {
        return this._socket
    }
Example #22
Source File: process.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
function doFindFreePort(startPort: number, giveUpAfter: number, clb: (port: number) => void): void {
  if (giveUpAfter === 0) {
    return clb(0);
  }

  const client = new Socket();

  // If we can connect to the port it means the port is already taken so we continue searching
  client.once("connect", () => {
    dispose(client);

    return doFindFreePort(startPort + 1, giveUpAfter - 1, clb);
  });

  client.once("data", () => {
    // this listener is required since node.js 8.x
  });

  client.once("error", (err: Error & { code?: string }) => {
    dispose(client);

    // If we receive any non ECONNREFUSED error, it means the port is used but we cannot connect
    if (err.code !== "ECONNREFUSED") {
      return doFindFreePort(startPort + 1, giveUpAfter - 1, clb);
    }

    // Otherwise it means the port is free to use!
    return clb(startPort);
  });

  client.connect(startPort, "127.0.0.1");

  function dispose(socket: Socket): void {
    try {
      socket.removeAllListeners("connect");
      socket.removeAllListeners("error");
      socket.end();
      socket.destroy();
      socket.unref();
    } catch (error) {
      console.error(error); // otherwise this error would get lost in the callback chain
    }
  }
}
Example #23
Source File: DevServer.ts    From web with MIT License 5 votes vote down vote up
private connections = new Set<Socket>();
Example #24
Source File: ipc.ts    From cloudmusic-vscode with MIT License 5 votes vote down vote up
private _socket?: Socket;
Example #25
Source File: supervisor.ts    From mysterium-vpn-desktop with MIT License 5 votes vote down vote up
conn?: Socket
Example #26
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 #27
Source File: socketManager.ts    From javascript-opensdk with Apache License 2.0 5 votes vote down vote up
/**
   * Opens a connection to the Agent development socket.
   *
   * @param {string} socketAddress The address for the socket
   * @param {number} socketPort The development socket port to connect to
   */
  public openSocket(socketAddress: string, socketPort: number): void {
    // Check if there is already a opened socket
    if (this.socket) {
      logger.debug('OpenSocket(): Socket already exists');
      return;
    }

    // Check if the socket is connected
    if (this.isConnected()) {
      logger.debug('open_socket(): Socket is already connected');
      return;
    }

    // Initialize the new socket
    this.socket = new Socket();

    // Create the socket options object
    const socketOptions: SocketConnectOpts = {
      host: socketAddress,
      port: socketPort,
    };

    this.socket
      .connect(socketOptions, () => {
        if (!this.isConnected()) {
          throw new Error('Failed connecting to Agent socket');
        }

        logger.debug(`Socket connection to ${socketAddress}:${socketPort} established successfully`);
      })
      .on('error', (res) => {
        logger.error(`Socket Connection Failed! message:${res.message}`);
        throw new Error(res.message);
      });
  }
Example #28
Source File: index.ts    From vircadia-metaverse with Apache License 2.0 5 votes vote down vote up
currentConnections: Map<number, Socket> = new Map<number, Socket>()
Example #29
Source File: gdbclient.ts    From rp2040js with MIT License 5 votes vote down vote up
private socket = new Socket();