|
| 1 | +--- |
| 2 | +title: ESP8266WiFi Client Class - Sketch Examples |
| 3 | +--- |
| 4 | + |
| 5 | +[ESP8266WiFi Library :back:](readme.md#client) |
| 6 | + |
| 7 | + |
| 8 | +## Client |
| 9 | + |
| 10 | +Let's write a simple client program to access a single web page and display its contents on a serial monitor. This is typical operation performed by a client to access server's API to retrieve specific information. For instance we may want to contact GitHub's API to periodically check the number of open issues reported on [esp8266 / Arduino](https://github.com/esp8266/Arduino/issues) repository. |
| 11 | + |
| 12 | + |
| 13 | +## Table of Contents |
| 14 | + * [Introduction](#introduction) |
| 15 | + * [Get Connected to Wi-Fi](#get-connected-to-wi-fi) |
| 16 | + * [Select a Server](#select-a-server) |
| 17 | + * [Instantiate the Client](#instantiate-the-client) |
| 18 | + * [Get Connected to the Server](#get-connected-to-the-server) |
| 19 | + * [Request the Data](#request-the-data) |
| 20 | + * [Read Reply from the Server](#read-reply-from-the-server) |
| 21 | + * [Now to the Sketch](#now-to-the-sketch) |
| 22 | + * [Test it Live](#test-it-live) |
| 23 | + * [Test it More](#test-it-more) |
| 24 | + * [Conclusion](#conclusion) |
| 25 | + |
| 26 | + |
| 27 | +### Introduction |
| 28 | + |
| 29 | +This time we are going to concentrate just on retrieving a web page contents sent by a server, to demonstrate basic client's functionality. Once you are able to retrieve information from a server, you should be able to phrase it and extract specific data you need. |
| 30 | + |
| 31 | + |
| 32 | +### Get Connected to Wi-Fi |
| 33 | + |
| 34 | +We should start with connecting the module to an access point to obtain an access to internet. The code to provide this functionality has been already discussed in chapter [Quick Start](readme.md#quick-start). Please refer to it for details. |
| 35 | + |
| 36 | + |
| 37 | +### Select a Server |
| 38 | + |
| 39 | +Once connected to the network we should connect to the specific server. Web address of this server is declared in `host` character string as below. |
| 40 | + |
| 41 | +```cpp |
| 42 | +const char* host = "www.example.com"; |
| 43 | +``` |
| 44 | +I have selected `www.example.com` domain name and you can select any other. Just check if you can access it using a web browser. |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +### Instantiate the Client |
| 50 | + |
| 51 | +Now we should declare a client that will be contacting the host (server): |
| 52 | + |
| 53 | +```cpp |
| 54 | +WiFiClient client; |
| 55 | +``` |
| 56 | + |
| 57 | + |
| 58 | +### Get Connected to the Server |
| 59 | + |
| 60 | +In next line we will connect to the host and check the connection result. Note `80`, that is the standard port number used for web access. |
| 61 | + |
| 62 | +```cpp |
| 63 | +if (client.connect(host, 80)) |
| 64 | +{ |
| 65 | + // we are connected to the host! |
| 66 | +} |
| 67 | +else |
| 68 | +{ |
| 69 | + // connection failure |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | + |
| 74 | +### Request the Data |
| 75 | + |
| 76 | +If connection is successful, we should send request the host to provide specific information we need. This is done using the [HTTP GET](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) request as in the following lines: |
| 77 | + |
| 78 | +```cpp |
| 79 | +client.print(String("GET /") + " HTTP/1.1\r\n" + |
| 80 | + "Host: " + host + "\r\n" + |
| 81 | + "Connection: close\r\n" + |
| 82 | + "\r\n" |
| 83 | + ); |
| 84 | +``` |
| 85 | + |
| 86 | +### Read Reply from the Server |
| 87 | + |
| 88 | +Then, while connection by our client is still alive (`while (client.connected())`, see below) we can read line by line and print out server's response: |
| 89 | + |
| 90 | +```cpp |
| 91 | +while (client.connected()) |
| 92 | +{ |
| 93 | + if (client.available()) |
| 94 | + { |
| 95 | + String line = client.readStringUntil('\n'); |
| 96 | + Serial.println(line); |
| 97 | + } |
| 98 | +} |
| 99 | +``` |
| 100 | + |
| 101 | +The inner `if (client.available())` is checking if there are any data available from the server. If so, then they are printed out. |
| 102 | + |
| 103 | +Once server sends all requested data it will disconnect and program will exit the `while` loop. |
| 104 | + |
| 105 | + |
| 106 | +### Now to the Sketch |
| 107 | + |
| 108 | +Complete sketch, including a case when contention to the server fails, is presented below. |
| 109 | + |
| 110 | +```cpp |
| 111 | +#include <ESP8266WiFi.h> |
| 112 | + |
| 113 | +const char* ssid = "********"; |
| 114 | +const char* password = "********"; |
| 115 | + |
| 116 | +const char* host = "www.example.com"; |
| 117 | + |
| 118 | + |
| 119 | +void setup() |
| 120 | +{ |
| 121 | + Serial.begin(115200); |
| 122 | + Serial.println(); |
| 123 | + |
| 124 | + Serial.printf("Connecting to %s ", ssid); |
| 125 | + WiFi.begin(ssid, password); |
| 126 | + while (WiFi.status() != WL_CONNECTED) |
| 127 | + { |
| 128 | + delay(500); |
| 129 | + Serial.print("."); |
| 130 | + } |
| 131 | + Serial.println(" connected"); |
| 132 | +} |
| 133 | + |
| 134 | + |
| 135 | +void loop() |
| 136 | +{ |
| 137 | + WiFiClient client; |
| 138 | + |
| 139 | + Serial.printf("\n[Connecting to %s ... ", host); |
| 140 | + if (client.connect(host, 80)) |
| 141 | + { |
| 142 | + Serial.println("connected]"); |
| 143 | + |
| 144 | + Serial.println("[Sending a request]"); |
| 145 | + client.print(String("GET /") + " HTTP/1.1\r\n" + |
| 146 | + "Host: " + host + "\r\n" + |
| 147 | + "Connection: close\r\n" + |
| 148 | + "\r\n" |
| 149 | + ); |
| 150 | + |
| 151 | + Serial.println("[Response:]"); |
| 152 | + while (client.connected()) |
| 153 | + { |
| 154 | + if (client.available()) |
| 155 | + { |
| 156 | + String line = client.readStringUntil('\n'); |
| 157 | + Serial.println(line); |
| 158 | + } |
| 159 | + } |
| 160 | + client.stop(); |
| 161 | + Serial.println("\n[Disconnected]"); |
| 162 | + } |
| 163 | + else |
| 164 | + { |
| 165 | + Serial.println("connection failed!]"); |
| 166 | + client.stop(); |
| 167 | + } |
| 168 | + delay(5000); |
| 169 | +} |
| 170 | +``` |
| 171 | + |
| 172 | + |
| 173 | +### Test it Live |
| 174 | + |
| 175 | +Upload sketch the module and open serial monitor. You should see a log similar to presented below. |
| 176 | + |
| 177 | +First, after establishing Wi-Fi connection, you should see confirmation, that client connected to the server and send the request: |
| 178 | + |
| 179 | +``` |
| 180 | +Connecting to sensor-net ........ connected |
| 181 | +
|
| 182 | +[Connecting to www.example.com ... connected] |
| 183 | +[Sending a request] |
| 184 | +``` |
| 185 | + |
| 186 | +Then, after getting the request, server will first respond with a header that specifies what type of information will follow (e.g. `Content-Type: text/html`), how long it is (like `Content-Length: 1270`), etc.: |
| 187 | + |
| 188 | +``` |
| 189 | +[Response:] |
| 190 | +HTTP/1.1 200 OK |
| 191 | +
|
| 192 | +Cache-Control: max-age=604800 |
| 193 | +Content-Type: text/html |
| 194 | +Date: Sat, 30 Jul 2016 12:30:45 GMT |
| 195 | +Etag: "359670651+ident" |
| 196 | +Expires: Sat, 06 Aug 2016 12:30:45 GMT |
| 197 | +Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT |
| 198 | +Server: ECS (ewr/15BD) |
| 199 | +Vary: Accept-Encoding |
| 200 | +X-Cache: HIT |
| 201 | +x-ec-custom-error: 1 |
| 202 | +Content-Length: 1270 |
| 203 | +Connection: close |
| 204 | +``` |
| 205 | + |
| 206 | +End of header is marked with an empty line and then you should see the HTML code of requested web page. |
| 207 | + |
| 208 | +``` |
| 209 | +<!doctype html> |
| 210 | +<html> |
| 211 | +<head> |
| 212 | + <title>Example Domain</title> |
| 213 | +
|
| 214 | + <meta charset="utf-8" /> |
| 215 | + <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> |
| 216 | + <meta name="viewport" content="width=device-width, initial-scale=1" /> |
| 217 | + <style type="text/css"> |
| 218 | +
|
| 219 | +(...) |
| 220 | +
|
| 221 | +</head> |
| 222 | +
|
| 223 | +<body> |
| 224 | +<div> |
| 225 | + <h1>Example Domain</h1> |
| 226 | + <p>This domain is established to be used for illustrative examples in documents. You may use this |
| 227 | + domain in examples without prior coordination or asking for permission.</p> |
| 228 | + <p><a href="http://www.iana.org/domains/example">More information...</a></p> |
| 229 | +</div> |
| 230 | +</body> |
| 231 | +</html> |
| 232 | +
|
| 233 | +[Disconnected] |
| 234 | +``` |
| 235 | + |
| 236 | +### Test it More |
| 237 | + |
| 238 | +In case server's web address is incorrect, or server is not accessible, you should see the following short and simple message on the serial monitor: |
| 239 | + |
| 240 | +``` |
| 241 | +Connecting to sensor-net ........ connected |
| 242 | +
|
| 243 | +[Connecting to www.wrong-example.com ... connection failed!] |
| 244 | +``` |
| 245 | + |
| 246 | + |
| 247 | +### Conclusion |
| 248 | + |
| 249 | +With this simple example we have demonstrated how to set up a client program, connect it to a server, request a web page and retrieve it. Now you should be able to write your own client program for ESP8266 and move to more advanced dialogue with a server, like e.g. using [HTTPS](https://en.wikipedia.org/wiki/HTTPS) protocol with the [Client Secure](readme.md#client-secure). |
| 250 | + |
| 251 | +For more client examples please check |
| 252 | + * [WiFiClientBasic.ino](https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino) - a simple sketch that sends a message to a TCP server |
| 253 | + * [WiFiClient.ino](https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino) - this sketch sends data via HTTP GET requests to data.sparkfun.com service. |
| 254 | + |
| 255 | + |
| 256 | +For the list of functions provided to manage clients, please refer to the [Client Class :arrow_right:](client-class.md) documentation. |
0 commit comments