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


TypeScript Socket.on方法代碼示例

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


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

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

示例2: setupSocket

	protected setupSocket(client: Socket): void  {
		var ffBuffer = new Buffer(0);
		client.on('data', (data) => {
			var newBuffer = Buffer.concat([ffBuffer, data], ffBuffer.length + data.length);
			var pos = 0;
			var parseResult;
			while (pos < newBuffer.length &&
						 (parseResult = this.parseFirefoxPacket(newBuffer, pos))) {
				this.onExecuteCommand(parseResult.body);
				pos = parseResult.lastPos;
			}
			if (pos < newBuffer.length) {
				ffBuffer = newBuffer.slice(pos);
			} else if (ffBuffer.length > 0) {
				ffBuffer = new Buffer(0);
			}
		});

		client.on('end', () => {
			client.end();
			console.log('client disconnected');
			this._state = 'disconnected';
			this.onDisconnect();
		});
		this._client = client;
	}
開發者ID:yurydelendik,項目名稱:vscode-ff-debug,代碼行數:26,代碼來源:ffProtocol.ts

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

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

示例6: resolve

		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

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

示例8: createServer

      this.server = createServer((socket:Socket) => {

        socket.on("data", (data) => {
          console.log(data);
        });

        socket.on("close", () => {
          console.log("disconnected");
        });
      });
開發者ID:no0dles,項目名稱:janner,代碼行數:10,代碼來源:server.ts

示例9: start

 start(connection: Socket): (req: ServerRequest, res: ServerResponse) => void {
     let messageProcessingService = this.container.resolve<MessageProcessingService>(MessageProcessingService);
     console.info(`client connected ${connection.remoteAddress}:${connection.remotePort}`);
     connection.on('end', () =>
         console.warn(`client ${connection.remoteAddress}:${connection.remotePort} disconnected`)
     );
     connection.on('data', function(data: string) {
         let request = JSON.parse(data);
         messageProcessingService.processRequest(request);
     });
     return function () {};
 }
開發者ID:yarrem,項目名稱:messageProcessingService,代碼行數:12,代碼來源:app.ts

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


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