ESP8266 Arduino: Socket Server

In this tutorial, we will check how to set a socket server on the ESP8266 running the Arduino core. As a socket client for testing, we will use Putty. The tests of this tutorial were performed using a DFRobot’s ESP8266 FireBeetle board.


Introduction

In this tutorial, we will check how to set a socket server on the ESP8266 running the Arduino core. As a socket client for testing, we will use Putty. You can download it for free.

If you are looking on how to set a socket server on a ESP32, then please check this tutorial.

The tests of this tutorial were performed using a DFRobot’s ESP8266 FireBeetle board.

 

The code

To get started, we need to include the ESP8266WiFi.h library, so we can connect the ESP8266 to a WiFi network.

Naturally, we will also need to know the credentials of the network, more precisely, the name (Service Set Identifier or, in short, SSID), and password. We will store them in two global variables, so they are at the top of our code and they are easy to change.

Additionally, we will need an object of class WiFiServer, which we will also declare as global. We will use this object to configure the socket server and to listen to connections from socket clients.

The constructor for the WiFiServer class receives as argument the port where the socket server will be listening to incoming connections. The port is specified as an integer.

Note that the port is one of the parameters that the socket client will need to know in order to be able to reach the socket server hosted on the ESP8266.

#include "ESP8266WiFi.h"

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPass";

WiFiServer wifiServer(80);

Now we can move on to the Arduino setup function, where we will start by opening a serial connection, to output the results of our program. We will also use the setup function to connect the ESP8266 to the WiFi network, so it can be reached by clients connected to that same network.

At the end of the setup function, we will call the begin method on the WiFiServer object. This method call is used to initialize the socket server. You can check the full setup function below.

void setup() {

  Serial.begin(115200);

  delay(1000);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting..");
  }

  Serial.print("Connected to WiFi. IP:");
  Serial.println(WiFi.localIP());

  wifiServer.begin();
}

We will handle the clients on the Arduino main loop. Since this implementation of the socket server is not asynchronous, we will need to poll the WiFiServer object periodically to check if there are available socket clients. For an asynchronous approach, please check this library.

So, to check if there is a client available, we need to call the available method on the WiFiServer object.

This method, which takes no arguments, will return an object of class WiFiClient. Nonetheless, this function is non-blocking, which means it will return a value even if no client is connected.

We can check if a client is indeed connected by using the connected method of the WiFiClient object. One particular thing about the WiFiClient class is that it overloads the C++ bool operator to return the value returned by the connected method, which means we can simply enclose the object on a IF condition to check if the client is connected.

WiFiClient client = wifiServer.available();

if (client) {
  // Client handling code
}

If the client is indeed connected, then we start reading for incoming data while the client is still connected. So we poll the WiFiClient object for data inside a while loop which will break as soon as the client disconnects.

if (client) {

    while (client.connected()) {
      // Poll for data
    }
}

Inside that loop, we check if there is data available to read by calling the available method on the WiFiClient object, which will return the number of bytes available to read, if there are any. If there aren’t any bytes to read, then the function will return zero.

When there are bytes to read, then we simply need to call the read method on the WiFiClient object. Upon reading a byte, we will print it to the serial console.

Note that we should do a small delay between each polling attempt for incoming bytes.

if (client) {

    while (client.connected()) {

      while (client.available()>0) {
        char c = client.read();
        Serial.write(c);
      }

      delay(10);
    }
}

As mentioned, we keep the loop until the client disconnects. When it does, we call the stop method on the WiFiClient object to free the resources and then we end the iteration of the Arduino loop function, so the next iteration starts again at the beginning, checking for new incoming clients.

You can check the full source code below.

#include "ESP8266WiFi.h"

const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPass";

WiFiServer wifiServer(80);

void setup() {

  Serial.begin(115200);

  delay(1000);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting..");
  }

  Serial.print("Connected to WiFi. IP:");
  Serial.println(WiFi.localIP());

  wifiServer.begin();
}

void loop() {

  WiFiClient client = wifiServer.available();

  if (client) {

    while (client.connected()) {

      while (client.available()>0) {
        char c = client.read();
        Serial.write(c);
      }

      delay(10);
    }

    client.stop();
    Serial.println("Client disconnected");

  }
}

 

Testing the code

To test the whole system, first start by compiling and uploading the code to the ESP8266 using the Arduino IDE. As soon as the procedure finishes, open the Arduino IDE serial monitor.

After the device connects to the WiFi network, it should print the local IP obtained. Copy that IP, since we will need to use it on Putty, to connect to the socket server.

Then, after downloading Putty, open it. On the menu, select “Raw” as connection type. On the “Host Name (or IP address)” text box put the IP you have just copied and on the “Port” text box put 80 (remember that this was the value we specified in the Arduino code for our socket server). You can check the mentioned configuration at figure 1.

Putty Socket Client to ESP32 Socket server

Figure 1 – Configuring Putty for a raw socket connection.

After clicking the “Open” button, a command line window should appear. There you can type and send data to the ESP8266.

If you go back to the serial monitor, you should see the content you have sent getting printed, as indicated in figure 2.

ESP8266 Arduino Core Socket Server TCP.png

Figure 2 – Reaching the ESP8266 socket server from Putty.

 

Related Posts

20 thoughts on “ESP8266 Arduino: Socket Server”

  1. Hey there,
    Why is if(client) working? I thought it is the return bytes from the client?

    WiFiClient client = wifiServer.available();
    if (client) {
    // Client handling code

    Best regards
    Dominik
    }

    1. Hi!

      The condition works because the WiFiClient class overloads the boolean C++ operator.

      It means that when you apply an IF condition to an object of that class, it will return a custom result accordingly to what is implemented for that class.

      In the case of the WiFiClient class, the boolean operator will return the result of calling the connected method, which will be true if the client is connected and false otherwise.

      And that is why you can apply the if to the object.

      Hope this clarifies 🙂

      Best regards,
      Nuno Santos

  2. Hey there,
    Why is if(client) working? I thought it is the return bytes from the client?
    WiFiClient client = wifiServer.available();
    if (client) {
    // Client handling code
    Best regards
    Dominik
    }

    1. Hi!
      The condition works because the WiFiClient class overloads the boolean C++ operator.
      It means that when you apply an IF condition to an object of that class, it will return a custom result accordingly to what is implemented for that class.
      In the case of the WiFiClient class, the boolean operator will return the result of calling the connected method, which will be true if the client is connected and false otherwise.
      And that is why you can apply the if to the object.
      Hope this clarifies 🙂
      Best regards,
      Nuno Santos

  3. Hi!
    Thanks for your interesting tutorial. I want to communicate via sockets to an Adafruit Feather Huzzah with ESP8266 WiFi for a future small drone project. But I don’t receive the IP from the ESP8266 access point server. This happens with a Windows 10 or an IPhone. The Arduino monitor is indicating endless “connecting”! Do you have an explanation?
    Best regards
    Jack

    1. Hi!

      You’re welcome, I’m happy to know you are finding the content interesting 🙂

      That message indicates that the ESP is trying to connect to the WiFi network.

      If it keeps printing it, it means it is not able to connect.

      The simplest possibility is having something wrong with the credentials, either the network name or the pass.

      Can you please check if you have some typo in your password or network name?

      Also, you are using one of your ESPs as a soft AP, right? Can you connect to the network it is hosting from another device, such as a computer?

      Best regards
      Nuno Santos

      1. Hi, thanks for your fast reply. I tested the same Esp8266 with the softAP mode with a sample from hackster Website (led on/off) in connection with an Android smartphone (Samsung Galaxy S4). It works fine. I used the same SSID and PW, but the Arduino IDE monitor indicates always “connecting” and no IP address is indicated.

        Best regards

        Jack

        1. You’re welcome 🙂

          Well to be honest I’m not sure what may be causing your problem.

          One thing you can try to help debugging is scanning the surrounding networks and check if it is in the list.

          Here is an example sketch:
          https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino

          I’ve not been working with the ESP8266 WiFi in a while, but I thing you can also try to look into the output of the status method and check if the returning value indicates what is the error you are experiencing.

          I think there is also a new method called waitForConnectResult which should be blocking and also return a status as output (I haven’t tested though). Taken from this sketch:
          https://github.com/esp8266/Arduino/blob/74819a763bfb6e9890a57411dcea4aba221a778d/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino

          Here is the output enum definition:
          https://github.com/esp8266/Arduino/blob/74819a763bfb6e9890a57411dcea4aba221a778d/libraries/ESP8266WiFi/src/include/wl_definitions.h#L50

          Hope this helps 🙂

          Best regards,
          Nuno Santos

  4. Hi!
    Thanks for your interesting tutorial. I want to communicate via sockets to an Adafruit Feather Huzzah with ESP8266 WiFi for a future small drone project. But I don’t receive the IP from the ESP8266 access point server. This happens with a Windows 10 or an IPhone. The Arduino monitor is indicating endless “connecting”! Do you have an explanation?
    Best regards
    Jack

    1. Hi!
      You’re welcome, I’m happy to know you are finding the content interesting 🙂
      That message indicates that the ESP is trying to connect to the WiFi network.
      If it keeps printing it, it means it is not able to connect.
      The simplest possibility is having something wrong with the credentials, either the network name or the pass.
      Can you please check if you have some typo in your password or network name?
      Also, you are using one of your ESPs as a soft AP, right? Can you connect to the network it is hosting from another device, such as a computer?
      Best regards
      Nuno Santos

      1. Hi, thanks for your fast reply. I tested the same Esp8266 with the softAP mode with a sample from hackster Website (led on/off) in connection with an Android smartphone (Samsung Galaxy S4). It works fine. I used the same SSID and PW, but the Arduino IDE monitor indicates always “connecting” and no IP address is indicated.
        Best regards
        Jack

        1. You’re welcome 🙂
          Well to be honest I’m not sure what may be causing your problem.
          One thing you can try to help debugging is scanning the surrounding networks and check if it is in the list.
          Here is an example sketch:
          https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino
          I’ve not been working with the ESP8266 WiFi in a while, but I thing you can also try to look into the output of the status method and check if the returning value indicates what is the error you are experiencing.
          I think there is also a new method called waitForConnectResult which should be blocking and also return a status as output (I haven’t tested though). Taken from this sketch:
          https://github.com/esp8266/Arduino/blob/74819a763bfb6e9890a57411dcea4aba221a778d/libraries/ESP8266WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino
          Here is the output enum definition:
          https://github.com/esp8266/Arduino/blob/74819a763bfb6e9890a57411dcea4aba221a778d/libraries/ESP8266WiFi/src/include/wl_definitions.h#L50
          Hope this helps 🙂
          Best regards,
          Nuno Santos

  5. Hello, first of all, thank you for providing this great tutorial!

    I have been able to test this out successfully using putty as the client. I am now trying to use an android TCP client app instead of putty to do the same thing, but seems that when I enter the same IP address and port, the socket gets connected briefly, then disconnects. I’ve tried 3 different apps so far, and all behaves the same.

    Do you have any ideas why this is? Any insight would be appreciated!

    1. Hi!

      You are welcome and thank you very much for the feedback 🙂

      Unfortunately I have no suggestion as I’ve never tried such Android apps :/

      Do you have problems if you use a different software other than putty in a computer? If it works, it might be a specific Android – ESP problem.

      You can also ask around the GitHub page of the ESP8266 arduino core, someone there might have already experienced that and maybe help.

      Let us know if you find a solution in the meanwhile 🙂

      Best regards,
      Nuno Santos

  6. Hello, first of all, thank you for providing this great tutorial!
    I have been able to test this out successfully using putty as the client. I am now trying to use an android TCP client app instead of putty to do the same thing, but seems that when I enter the same IP address and port, the socket gets connected briefly, then disconnects. I’ve tried 3 different apps so far, and all behaves the same.
    Do you have any ideas why this is? Any insight would be appreciated!

    1. Hi!
      You are welcome and thank you very much for the feedback 🙂
      Unfortunately I have no suggestion as I’ve never tried such Android apps :/
      Do you have problems if you use a different software other than putty in a computer? If it works, it might be a specific Android – ESP problem.
      You can also ask around the GitHub page of the ESP8266 arduino core, someone there might have already experienced that and maybe help.
      Let us know if you find a solution in the meanwhile 🙂
      Best regards,
      Nuno Santos

  7. Hi, thank u for the tutorial
    I am new to using micro processors but I have programmed http services, may I ask a question, why do we need that delay(10) at the end?

  8. Hi! Thanks for the article. If I want to send strings to putty in addition to writing from Putty. What command lines should I add?

  9. Hi! Thank you for sharing your experience .
    I have a question,,, This tutorial the ESP play SERVER role and reliable working for me.
    But I want to use TCP socket as CLIENT role.
    In such a way that, Putty is a server (listen at the port 2000) and 30 ESP client connect to server.
    Can you help me or any suggestion?
    Thanks,

Leave a Reply to antepherCancel reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading