Server

Setting up web a server on ESP8266 requires very little code and is surprisingly straightforward. This is thanks to functionality provided by the versatile ESP8266WiFi library.

The purpose of this example will be to prepare a web page that can be opened in a web browser. This page should show the current raw reading of ESP’s analog input pin.

Table of Contents

The Object

We will start off by creating a server object.

WiFiServerserver(80);

The server responds to clients (in this case - web browsers) on port 80, which is a standard port web browsers talk to web servers.

The Page

Then let’s write a short functionprepareHtmlPage(), that will return aString class variable containing the contents of the web page. We will then pass this variable to server to pass it over to a client.

StringprepareHtmlPage(){StringhtmlPage=String("HTTP/1.1 200 OK\r\n")+"Content-Type: text/html\r\n"+"Connection: close\r\n"+//theconnectionwillbeclosedaftercompletionoftheresponse"Refresh: 5\r\n"+//refreshthepageautomaticallyevery5sec"\r\n"+"<!DOCTYPE HTML>"+"<html>"+"Analog input:  "+String(analogRead(A0))+"</html>"+"\r\n";returnhtmlPage;}

The function does nothing fancy but just puts together a text header andHTML contents of the page.

Header First

The header is to inform client what type of contents is to follow and how it will be served:

Content-Type:text/htmlConnection:closeRefresh:5

In our example the content type istext/html, the connection will be closed after serving and the content should be requested by the client again every 5 seconds. The header is concluded with an empty line\r\n. This is to distinguish header from the content to follow.

<!DOCTYPE HTML><html>Analog input:  [Value]</html>

The content contains two basicHTML tags, one to denote HTML document type<!DOCTYPEHTML> and another to mark beginning<html> and end</html> of the document. Inside there is a raw value read from ESP’s analog inputanalogRead(A0) converted to theString type.

String(analogRead(A0))

The Page is Served

Serving of this web page will be done in theloop() where server is waiting for a new client to connect and send some data containing a request:

voidloop(){WiFiClientclient=server.available();if(client){//wehaveanewclientsendingsomerequest}}

Once a new client is connected, server will read the client’s request and print it out on a serial monitor.

while(client.connected()){if(client.available()){Stringline=client.readStringUntil('\r');Serial.print(line);}}

Request from the client is marked with an empty new line. If we find this mark, we can send back the web page and exitwhile() loop usingbreak.

if(line.length()==1&&line[0]=='\n'){client.println(prepareHtmlPage());break;}

The whole process is concluded by stopping the connection with client:

client.stop();

Put it Together

Complete sketch is presented below.

#include <ESP8266WiFi.h>constchar*ssid="********";constchar*password="********";WiFiServerserver(80);voidsetup(){Serial.begin(115200);Serial.println();Serial.printf("Connecting to%s ",ssid);WiFi.begin(ssid,password);while(WiFi.status()!=WL_CONNECTED){delay(500);Serial.print(".");}Serial.println(" connected");server.begin();Serial.printf("Web server started, open%s in a web browser\n",WiFi.localIP().toString().c_str());}//prepareawebpagetobesendtoaclient(webbrowser)StringprepareHtmlPage(){StringhtmlPage=String("HTTP/1.1 200 OK\r\n")+"Content-Type: text/html\r\n"+"Connection: close\r\n"+//theconnectionwillbeclosedaftercompletionoftheresponse"Refresh: 5\r\n"+//refreshthepageautomaticallyevery5sec"\r\n"+"<!DOCTYPE HTML>"+"<html>"+"Analog input:  "+String(analogRead(A0))+"</html>"+"\r\n";returnhtmlPage;}voidloop(){WiFiClientclient=server.available();//waitforaclient(webbrowser)toconnectif(client){Serial.println("\n[Client connected]");while(client.connected()){//readlinebylinewhattheclient(webbrowser)isrequestingif(client.available()){Stringline=client.readStringUntil('\r');Serial.print(line);//waitforendofclient's request, that is marked with an empty lineif(line.length()==1&&line[0]=='\n'){client.println(prepareHtmlPage());break;}}}delay(1);//givethewebbrowsertimetoreceivethedata//closetheconnection:client.stop();Serial.println("[Client disonnected]");}}

Get it Run

Updatessid andpassword in sketch to match credentials of your access point. Load sketch to ESP module and open a serial monitor. First you should see confirmation that module connected to the access point and the web server started.

Connectingtosensor-net........connectedWebserverstarted,open192.168.1.104inawebbrowser

Enter provided IP address in a web browser. You should see the page served by ESP8266:

Output from server in a web browser

alt text

The page would be refreshed every 5 seconds. Each time this happens, you should see a request from the client (your web browser) printed out on the serial monitor:

[Clientconnected]GET/HTTP/1.1Accept:text/html,application/xhtml+xml,*/*Accept-Language:en-USUser-Agent:Mozilla/5.0(WindowsNT6.1;WOW64;Trident/7.0;rv:11.0)likeGeckoAccept-Encoding:gzip,deflateHost:192.168.1.104DNT:1Connection:Keep-Alive[clientdisonnected]

What Else?

Looking onclient examples you will quickly find out the similarities in protocol to the server. The protocol starts with a header that contains information what communication will be about. It contains what content type is communicated or accepted liketext/html. It states whether connection will be kept alive or closed after submission of the header. It contains identification of the sender likeUser-Agent:Mozilla/5.0(WindowsNT6.1), etc.

Conclusion

The above example shows that a web server on ESP8266 can be set up in almost no time. Such server can easily stand up requests from much more powerful hardware and software like a PC with a web browser. Check out other classes likeESP8266WebServer that let you program more advanced applications.

If you like to try another server example, check outWiFiWebServer.ino, that provides functionality of toggling the GPIO pin on and off out of a web browser.

For the list of functions provided to implement and manage servers, please refer to theServer Class documentation.