available()

描述

回傳目前與 Client 連線的伺服端傳送過來的資料量,這些資料都是目前可以讀取的。

available() 是從 Stream 繼承而來。

語法


client.available()

參數

無參數

回傳

int:目前可以讀取的資料量,以位元組為單位

範例

#include <WiFi.h>

char ssid[] = "myNetwork";          // 無線網路的 SSID
char pass[] = "myPassword";   // WPA 的密碼

int status = WL_IDLE_STATUS;
char servername[]="google.com";  // Google

WiFiClient client;

void setup() {
  Serial.begin(9600);
  Serial.println("Attempting to connect to WPA network...");
  Serial.print("SSID: ");
  Serial.println(ssid);

  status = WiFi.begin(ssid, pass);
  if ( status != WL_CONNECTED) { 
    Serial.println("Couldn't get a wifi connection");
    while(true);
  } 
  else {
    Serial.println("Connected to wifi");
    Serial.println("\nStarting connection...");
    // 如果成功連線,透過序列埠印出訊息
    if (client.connect(servername, 80)) {
      Serial.println("connected");
      // 傳送 HTTP 封包
      client.println("GET /search?q=arduino HTTP/1.0");
      client.println();
    }
  }
}

void loop() {
  // 如果有伺服端傳送過來的資料,讀取這些資料並且透過序列埠印出
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // 如果與伺服器的連線中斷,關閉 client
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    for(;;)
      ;
  }
}

函式庫參考主頁面

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.