當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript Socket.connect方法代碼示例

本文整理匯總了TypeScript中net.Socket.connect方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Socket.connect方法的具體用法?TypeScript Socket.connect怎麽用?TypeScript Socket.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net.Socket的用法示例。


在下文中一共展示了Socket.connect方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: Promise

    return new Promise((resolve) => {
      this.socket.connect(this.port, this.address, () => {
        console.log('Connected');
        this.socket.write('Hello, server! Love, Client.');
        
        resolve();
      });

      this.socket.on('data', (data) => {
        console.log('Received: ' + data);
        //this.socket.destroy(); // kill client after server's response
        this.socket.end();
      });

      this.socket.on('timeout', () => {
        console.log('Connection closed');
      });

      this.socket.on('close', (hadError: boolean) => {
        console.log('Connection closed');
      });

      this.socket.on('end', () => {
        console.log('Connection closed');
      });

      this.socket.on("error", (error: Error) => {
        console.log(error);
      });
    });
開發者ID:no0dles,項目名稱:janner,代碼行數:30,代碼來源:client.ts

示例2: guessIdleTimeout

/*
If we connect to the machine, send one initial query and then stop, how long
can we idle until the machine terminates our connection?

Testing shows that this doesn't seem to be one consistent timeout, and that
instead it's however long it takes until the wifi flakes out a little bit.
*/
function guessIdleTimeout() {
  log.info('Estimating idle time...');
  let start = Date.now();

  let sock = new Socket();
  sock.setTimeout(10000);
  killOnProcessExit(sock);
  sock.on('data', function (data) {
    log.inbound(escapeUnprintables(data));
    if (String(data) === '*HELLO*') {
      setTimeout(function () {
        let msg = Checksum.attach('r00000001');
        log.outbound(msg);
        sock.write(msg);
      }, 100);
    }
  });
  sock.on('error', err => {
    let elapsed = Date.now() - start;
    log.info('elapsed', elapsed, 'ms');
    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');
    setInterval(() => {
      let elapsed = Date.now() - start;
      log.info('elapsed', elapsed, 'ms');
    }, 10000);
  });
}
開發者ID:jffry,項目名稱:rocket-r60v,代碼行數:39,代碼來源:measure.ts

示例3:

		return new Promise<boolean>((resolve, reject) => {
			let isResolved = false;
			const socket = new net.Socket();

			socket.connect(this.port, '127.0.0.1', () => {
				socket.write(Buffer.from([0, 0, 0, 1, 1]));
			});
			socket.on("data", (data: any) => {
				isResolved = true;
				socket.destroy();
				resolve(true);
			});
			socket.on("error", () => {
				if (!isResolved) {
					isResolved = true;
					resolve(false);
				}
			});
			socket.on("close", () => {
				if (!isResolved) {
					isResolved = true;
					resolve(false);
				}
			});
		});
開發者ID:NathanaelA,項目名稱:nativescript-cli,代碼行數:25,代碼來源:android-device-livesync-service.ts

示例4: transmit

    public transmit(host: string, port: number, data: string, callback: TCPClientCallback) {
        let self = this;
        let client = new net.Socket();
        LoggingHelper.info(Logger, "Forwarding " + host + ":" + port);

        client.on("error", function (e: any) {
            console.log("TCPClient Error: " + e.message);
            if (e.code ===  "ECONNREFUSED") {
                callback(null, NetworkErrorType.CONNECTION_REFUSED, e.message);
            } else {
                callback(null, NetworkErrorType.OTHER, e.message);
            }
        });

        client.connect(port, host, function () {
            // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
            client.write(data);
        });


        // Add a 'data' event handler for the client socket
        // data is what the server sent to this socket
        client.on("data", function(data: Buffer) {
            callback(data, null, null);
        });

        // Add a 'close' event handler for the client socket
        client.on("close", function(had_error: boolean) {
            LoggingHelper.debug(Logger, "Connection closed ID: " + self.id + " HadError: " + had_error);
            if (self.onCloseCallback !== undefined && self.onCloseCallback !== null) {
                self.onCloseCallback();
            }
        });
    }
開發者ID:debmalya,項目名稱:bst,代碼行數:34,代碼來源:tcp-client.ts

示例5: function

  return new Promise<any>((resolve, reject) => {
    const client = new net.Socket();
    let resolved = false;
    let buffer = "";

    client.connect(port, host, function() {
      client.write(JSON.stringify(msg));
    });

    client.on('error', function(err) {
      if (!resolved) {
        resolved = true;
        reject(err);
      }
    });

    client.on('data', function(data) {
      buffer += data.toString();
    });

    client.on('close', function() {
      if (!resolved) {
        resolved = true;
        resolve(JSON.parse(buffer));
      }
    });
  });
開發者ID:ncave,項目名稱:Fable,代碼行數:27,代碼來源:net-client.ts

示例6: Socket

      server.listen(8788, 'localhost', () => {
        /**
         * Client
         */
        const client = new Socket()
        client.connect(8788, 'localhost', () => {
          log.silly('Doctor', 'testTcp() client connected')
          client.write('ding')
        })

        client.on('data', () => {
          /**
           * Promise Resolve
           */
          resolve(true)

          client.destroy() // kill client after server's response
        })
        /**
         * Promise Reject
         */
        client.on('error', reject)

        client.on('close', _ => server.close())
      })
開發者ID:KiddoLin,項目名稱:wechaty,代碼行數:25,代碼來源:doctor.ts

示例7: 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

示例8: function

 socket.on('command', function (msg) {
     //io.emit('text change', msg);
     client.connect(PORT, HOST, function () {
         console.log('\nCONNECTED TO: ' + HOST + ':' + PORT + '\n- Command:' + msg);
         // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
         client.write(msg);
     });
 });
開發者ID:sipahigokhan,項目名稱:NetduinoSamples,代碼行數:8,代碼來源:server.ts

示例9: 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

示例10: accept

conn.on('x11', (info: any, accept: any, reject: any) => {
    var xserversock = new net.Socket();
    xserversock.on('connect', () => {
        var xclientsock = accept();
        xclientsock.pipe(xserversock).pipe(xclientsock);
    });
    // connects to localhost:0.0
    xserversock.connect(6000, 'localhost');
});
開發者ID:Jeremy-F,項目名稱:DefinitelyTyped,代碼行數:9,代碼來源:ssh2-tests.ts


注:本文中的net.Socket.connect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。