• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript net.createConnection函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中net.createConnection函数的典型用法代码示例。如果您正苦于以下问题:TypeScript createConnection函数的具体用法?TypeScript createConnection怎么用?TypeScript createConnection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: sendCommand

export function sendCommand(tag: string, cmd: string, callback: (code) => void) {
  let cmdMap = {
    'stop': COMMAND.STOP,
    'restart': COMMAND.RESTART,
    'status': COMMAND.STATUS,
    'statusjson': COMMAND.STATUSJSON,
  };
  
  let command = cmdMap[cmd.toLowerCase()];
  
  if (!command) {
    console.error('Command is not supported');
    return callback(1);
  }
  
  let path = util.format('/tmp/lightsword-%s.sock', tag);
  let socket = net.createConnection(path, async () => {
    await socket.writeAsync(new Buffer([command]));
    let msg = await socket.readAsync();
    console.info(msg.toString('utf8'));
    socket.destroy();
    callback(0);
  });
  
  socket.on('error', (err: Error) => { console.info(`${tag} is not running or unix socket error.`); callback(1); });
  socket.setTimeout(5 * 1000);
}
开发者ID:52M,项目名称:LightSword,代码行数:27,代码来源:ipc.ts


示例2: it

	it('should close the socket keeping the socket open but then keeping it no longer open', function (done) {
		this.timeout(0);

		var sock = net.createConnection(9002, 'localhost');

		sock.on('connect', function () {
			var socket = new TCPSocket(sock, socket_opts);

			var closeList1 = function () {
				throw new Error('Should not close socket');
			};

			socket.once('close', closeList1);

			socket.setKeepOpen(true);

			setTimeout(function () {
				socket.removeListener('close', closeList1);

				socket.once('close', function () {
					done();
				});

				socket.setKeepOpen(false);
			}, 3000);
		});
	});
开发者ID:jcostantini,项目名称:core,代码行数:27,代码来源:TCPSocket.ts


示例3: async

  const listen = async () => {
    listening = true

    // We want to keep trying to reconnect here, so the dashboard can be restarted.
    while (true) {
      console.log('Connecting to monitoring server at', host)
      const socket = net.createConnection(+port, host)
      serveToSocket(localStore, socket)

      socket.on('connect', () => {console.log('connected')})

      await new Promise(resolve => {
        socket.on('error', err => {
          console.warn('Error connecting to monitoring server', err.message)
        })
        socket.on('close', hadError => {
          // console.log('closed', hadError)
          resolve()
        })
      })

      // Wait 3 seconds before trying to connect again.
      await new Promise(resolve => setTimeout(resolve, 3000))
    }
  }
开发者ID:josephg,项目名称:statecraft,代码行数:25,代码来源:monitor.ts


示例4: handleOutbound

function handleOutbound(client: net.Socket, host: string, port: number, desiredIv: Buffer, options: HandshakeOptions) {
  
  let proxy = net.createConnection({ port, host }, async () => {
    let success = new Buffer([0x01, 0x00]);
    let randomLength = Number((Math.random() * 64).toFixed());
    let reply = Buffer.concat([success, new Buffer(randomLength)]);
    
    let cipher = cryptoEx.createCipher(options.cipherAlgorithm, options.password, desiredIv).cipher;
    await client.writeAsync(cipher.update(reply));
    let decipher = cryptoEx.createDecipher(options.cipherAlgorithm, options.password, options.iv);
    
    let speed = options.speed;
    
    let clientStream = speed > 0 ? client.pipe(new SpeedStream(speed)) : client;
    clientStream.pipe(decipher).pipe(proxy);
    
    let proxyStream = speed > 0 ? proxy.pipe(new SpeedStream(speed)) : proxy;
    proxyStream.pipe(cipher).pipe(client);
  });
  
  function dispose() {
    client.dispose();
    proxy.dispose();
  }
  
  proxy.on('error', dispose);
  proxy.on('end', dispose);
  client.on('error', dispose);
  client.on('end', dispose);
  
  proxy.setTimeout(options.timeout * 1000);
  client.setTimeout(options.timeout * 1000);
}
开发者ID:Amonhuz,项目名称:LightSword,代码行数:33,代码来源:tcp.ts


示例5: function

      _this.resolve(endpoint, function (err, resolved) {
        if (!_this.connecting) {
          callback(new Error(CONNECTION_CLOSED_ERROR_MSG))
          return
        }
        if (resolved) {
          debug('resolved: %s:%s', resolved.host, resolved.port)
          _this.stream = createConnection(resolved)
          _this.sentinelIterator.reset(true)
          callback(null, _this.stream)
        } else {
          const endpointAddress = endpoint.host + ':' + endpoint.port
          const errorMsg = err
            ? 'failed to connect to sentinel ' + endpointAddress + ' because ' + err.message
            : 'connected to sentinel ' + endpointAddress + ' successfully, but got an invalid reply: ' + resolved

          debug(errorMsg)

          eventEmitter('sentinelError', new Error(errorMsg))

          if (err) {
            lastError = err
          }
          connectToNext()
        }
      })
开发者ID:zeratul1,项目名称:ioredis,代码行数:26,代码来源:index.ts


示例6: connectServer

 static connectServer(client: net.Socket, dst: { port: number, addr: string }, request: Buffer, timeout: number) {
   
   let proxySocket = net.createConnection(dst.port, dst.addr, async () => {
     let reply = new Buffer(request.length);
     request.copy(reply);
     reply[0] = 0x05;
     reply[1] = 0x00;
     
     await client.writeAsync(reply);
     
     proxySocket.pipe(client);
     client.pipe(proxySocket);
   });
   
   function dispose() {
     proxySocket.dispose();
     client.dispose();
   }
   
   proxySocket.on('end', dispose);
   proxySocket.on('error', dispose);
   client.on('end', dispose);
   client.on('error', dispose);
   
   proxySocket.setTimeout(timeout);
   client.setTimeout(timeout);
 }
开发者ID:52M,项目名称:LightSword,代码行数:27,代码来源:localProxyServer.ts


示例7: connect

	connect(host: string, port: number, query: string, callback: IConnectCallback): void {
		const errorListener = (err: any) => callback(err, undefined);

		const socket = net.createConnection({ host: host, port: port }, () => {
			socket.removeListener('error', errorListener);

			// https://tools.ietf.org/html/rfc6455#section-4
			const buffer = Buffer.alloc(16);
			for (let i = 0; i < 16; i++) {
				buffer[i] = Math.round(Math.random() * 256);
			}
			const nonce = buffer.toString('base64');

			let headers = [
				`GET ws://${host}:${port}/?${query}&skipWebSocketFrames=true HTTP/1.1`,
				`Connection: Upgrade`,
				`Upgrade: websocket`,
				`Sec-WebSocket-Key: ${nonce}`
			];
			socket.write(headers.join('\r\n') + '\r\n\r\n');

			const onData = (data: Buffer) => {
				const strData = data.toString();
				if (strData.indexOf('\r\n\r\n') >= 0) {
					// headers received OK
					socket.off('data', onData);
					callback(undefined, new NodeSocket(socket));
				}
			};
			socket.on('data', onData);
		});
		socket.once('error', errorListener);
	}
开发者ID:PKRoma,项目名称:vscode,代码行数:33,代码来源:nodeWebSocketFactory.ts


示例8: createClientSocket

function createClientSocket(endpointUrl: string): Socket {
    // create a socket based on Url
    const ep = parseEndpointUrl(endpointUrl);
    const port = parseInt( ep.port!, 10);
    const hostname = ep.hostname!;
    let socket: Socket;
    switch (ep.protocol) {
        case "opc.tcp:":

            socket = createConnection({ host: hostname, port });

            // Setting true for noDelay will immediately fire off data each time socket.write() is called.
            socket.setNoDelay(true);

            socket.setTimeout(0);

            socket.on("timeout", () => {
                debugLog("Socket has timed out");
            });

            return socket;
        case "fake:":
            socket = getFakeTransport();
            assert(ep.protocol === "fake:", " Unsupported transport protocol");
            process.nextTick(() => socket.emit("connect"));
            return socket;

        case "websocket:":
        case "http:":
        case "https:FF":
        default:
            throw new Error("this transport protocol is currently not supported :" + ep.protocol);

    }
}
开发者ID:node-opcua,项目名称:node-opcua,代码行数:35,代码来源:client_tcp_transport.ts


示例9: attach

export function attach({
  reader: _reader,
  writer: _writer,
  proc,
  socket,
}: Attach) {
  let writer;
  let reader;

  logger.debug('proc');
  logger.debug(proc);
  if (socket) {
    const client = createConnection(socket);
    writer = client;
    reader = client;
  } else if (_reader && _writer) {
    writer = _writer;
    reader = _reader;
  } else if (proc) {
    writer = proc.stdin;
    reader = proc.stdout;
  }

  if (writer && reader) {
    const neovim = new NeovimClient({ logger });
    neovim.attachSession({
      writer,
      reader,
    });
    return neovim;
  }
  throw new Error('Invalid arguments, could not attach');
}
开发者ID:billyvg,项目名称:node-client,代码行数:33,代码来源:attach.ts


示例10: before

	before(function (done) {
		var sock = net.createConnection(9002, 'localhost');

		sock.on('connect', function () {
			socket = new TCPSocket(sock, socket_opts);
			done();
		});
	});
开发者ID:jcostantini,项目名称:core,代码行数:8,代码来源:TCPSocket.ts



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript net.createServer函数代码示例发布时间:2022-05-25
下一篇:
TypeScript net.connect函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap