当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Socket.once方法代码示例

本文整理汇总了TypeScript中net.Socket.once方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Socket.once方法的具体用法?TypeScript Socket.once怎么用?TypeScript Socket.once使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.Socket的用法示例。


在下文中一共展示了Socket.once方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: doFindFreePort

function doFindFreePort(startPort: number, giveUpAfter: number, clb: (port: number) => void): void {
	if (giveUpAfter === 0) {
		return clb(0);
	}

	const client = new net.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');
}
开发者ID:VishalMadhvani,项目名称:vscode,代码行数:32,代码来源:ports.ts

示例2: readByte

function readByte(socket: Socket, offset: number, onResult: (readable: boolean, value?: number)=>void) {
  //validate
  if (offset < 0 || offset > 0xffff) {
    throw new RangeError("Offset must be a 16-bit integer from 0x0000 to 0xffff, inclusive");
  }
  //send
  socket.once('data', gotData);
  socket.once('error', gotError);
  let timeout = setTimeout(retry, 10000);
  function removeListeners() {
    socket.removeListener('data', gotData);
    socket.removeListener('error', gotError);
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
  }

  let message = Checksum.attach(`r${to4hex(offset)}0001`);
  log.outbound(message);
  socket.write(message);

  function retry() {
    removeListeners();
    log.info('Retrying...');
    setImmediate(readByte, socket, offset, onResult);
  }

  function gotError(err) {
    log.error(err);
    removeListeners();
  }

  function gotData(data) {
    if (data) data = String(data);
    log.inbound(data);
    let m = null;
    try {
      m = new Message(data);
    } catch (ex) {
      log.error(ex);
      retry();
      return;
    }
    removeListeners();
    let isReadable = m.bytes.length() > 4;
    if(isReadable) {
      setImmediate(onResult, true, m.bytes.getByte(4));
    } else {
      setImmediate(onResult, false, null);
    }
  }

}
开发者ID:jffry,项目名称:rocket-r60v,代码行数:54,代码来源:measure.ts

示例3: setInterval

	request.once('socket', (socket: Socket) => {
		const onSocketConnect = (): void => {
			progressInterval = setInterval(() => {
				const lastUploaded = uploaded;
				/* istanbul ignore next: see #490 (occurs randomly!) */
				const headersSize = (request as any)._header ? Buffer.byteLength((request as any)._header) : 0;
				uploaded = socket.bytesWritten - headersSize;

				// Don't emit events with unchanged progress and
				// prevent last event from being emitted, because
				// it's emitted when `response` is emitted
				if (uploaded === lastUploaded || uploaded === uploadBodySize) {
					return;
				}

				emitter.emit('uploadProgress', {
					percent: uploadBodySize ? uploaded / uploadBodySize : 0,
					transferred: uploaded,
					total: uploadBodySize
				});
			}, uploadEventFrequency);
		};

		/* istanbul ignore next: hard to test */
		if (socket.connecting) {
			socket.once('connect', onSocketConnect);
		} else if (socket.writable) {
			// The socket is being reused from pool,
			// so the connect event will not be emitted
			onSocketConnect();
		}
	});
开发者ID:sindresorhus,项目名称:got,代码行数:32,代码来源:progress.ts

示例4: listener

 return function listener(socket: Socket) {
   state.connectionId += 1;
   (socket as any).__waiConId__ = state.connectionId;
   socket.once('close', () => {
     delete state.connections[(socket as any).__waiConId__];
   });
   state.connections[(socket as any).__waiConId__] = socket;
 };
开发者ID:syaiful6,项目名称:jonggrang,代码行数:8,代码来源:run.ts

示例5: memoryMap

function memoryMap() {
  log.info('Reading memory...');

  //build up the socket
  let sock = new Socket();
  sock.setTimeout(10000);
  killOnProcessExit(sock);
  sock.on('error', err => {
    log.error(err);
    process.exit(1);
  });
  log.info('Connecting to %s:%s ...', DEST_HOST, DEST_PORT);

  sock.connect(DEST_PORT, DEST_HOST, function () {
    log.info('Connected');
  });

  //wait for first *HELLO* before starting the polling
  sock.once('data', function(data) {
    if (data) data = String(data);
    log.inbound(data);
    setTimeout(pollingLoop, 150);
  });
  //polling loop

  //store succesfully-read values here
  let values:(number|null)[] = new Array(0xFFFF);
  for (let i = 0; i < values.length; i++) {
    values[i] = 0;
  }
  let offset = 0x00;
  const startTime = Date.now();
  function pollingLoop() {
    readByte(sock, offset, (readable:boolean, value?:number) => {
      log.normal('byte', to4hex(offset), readable ? STATUS_OK : STATUS_ERR, value);
      //forecast ETA
      let elapsed = Date.now() - startTime;
      let total = elapsed * (0xffff / (offset + 1));
      let remain = total - elapsed;
      log.info('progress: elapsed', Math.round(elapsed/1000), 'sec; estimated remain', Math.round(remain / 1000), 'sec');
      //write to file... occasionally
      values[offset] = readable ? value : null;
      if (offset % 0x100 === 0) {
        log.info('SAVING RESULTS TO DISK');
        fs.writeFileSync('memscan.json', JSON.stringify(values));
      }
      //next
      offset += 1;
      if (offset <= 0xffff) {
        setTimeout(pollingLoop, 150);
      } else {
        log.info('SAVING RESULTS TO DISK');
        fs.writeFileSync('memscan.json', JSON.stringify(values));
        process.exit(0);
      }
    });
  }
}
开发者ID:jffry,项目名称:rocket-r60v,代码行数:58,代码来源:measure.ts

示例6: constructor

	constructor(sock: Socket) {
		this._sock = sock;
		this._sock.once("error", err => {
			if (!this._d)
				this._d = defer();
			if (this._d.pending)
				this._d.reject(err);
		});
	}
开发者ID:dcby,项目名称:smtp-receiver,代码行数:9,代码来源:Loop.ts

示例7: clearTimeout

 return new Promise<void>((resolve) => {
   if (this.timeout) {
     clearTimeout(this.timeout);
     this.timeout = null;
   }
   if (this.connectingSubscription) {
     this.connectingSubscription.unsubscribe();
     this.connectingSubscription = null;
   }
   this.socket.removeAllListeners();
   this.socket.once("close", () => resolve());
   this.socket.destroy();
   this.socket = null;
 });
开发者ID:svi3c,项目名称:rx-messaging,代码行数:14,代码来源:ClientConnector.ts

示例8: setTimeout

    const connect = () => {
      attempt++;

      const socket = new net.Socket();
      socket.once('error', () => {
        if (attempt < maxAttempts) {
          setTimeout(connect, retryIntervalMs);
        } else {
          reject(new errors.ServerUnreachable());
        }
      });

      if (timeout > 0) {
        socket.setTimeout(timeout);
      }

      socket.connect({host, port}, () => {
        socket.end();
        fulfill();
      });
    };
开发者ID:hlyu368,项目名称:outline-client,代码行数:21,代码来源:connectivity.ts

示例9: sock_readable

	private sock_readable(options) {
		let chunk = this._sock.read();

		if (!chunk) {
			this.resolve(null);
			return;
		}

		if (this._tail) {
			chunk = chunk ? Buffer.concat([this._tail, chunk], this._tail.length + chunk.length) : this._tail;
			this._tail = null;
		}

		let tail = this.processChunk(chunk, options.data);

		if (tail.length)
			this._tail = tail;

		// if no data has been processed - receive and process more data
		if (this.isPending)
			this._sock.once("readable", this.sock_readable.bind(this, options));
	}
开发者ID:dcby,项目名称:smtp-receiver,代码行数:22,代码来源:Loop.ts

示例10: Error

      this.link.connect(this.port, this.address, () => {
        this.link.on('error', (err: Error) => {
          this.link.end();
          throw new Error('An error occurred: ' + err.message);
        });

        //this.link.on('close', () => {
        //  console.log('whip connector: link closed');
        //});
        //this.link.on('finish', () => {
        //});
        this.messageBuffer = new Buffer([]);

        //read once for auth challenge
        this.link.once('readable', () => {
          let chunk: Buffer = this.link.read()
          if (!chunk) return;

          let ch = new AuthChallenge(chunk);
          let r = new AuthResponse(this.password, ch);

          this.link.write(r.response);

          // read once for auth response
          this.link.once('readable', () => {
            let chunk: Buffer = this.link.read()
            if (!chunk) return;
            let resp = new AuthConfirmation(chunk);

            if (resp.success){
              this.link.on('readable', () => this.dataChunker(this.link.read()));
              resolve(null);
            }
            else
              throw new Error('Auth failed to whip server')
          });
        });
      })
开发者ID:M-O-S-E-S,项目名称:mgm,代码行数:38,代码来源:Whip.ts


注:本文中的net.Socket.once方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。