Use Arduino development ESP32 (08): TCP Client and TCP Server use

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Naisu_kun/article/details/87125845

purpose

TCP is a commonly used network application functionality, many advanced features also based on TCP, TCP can learn to use to develop a lot of network applications.

TCP Client

TCP Client is mainly used to access the server, a lot of things that can be accessed by devices outside the network mainly work in TCP Client. Take the initiative to access the external device servers, to establish a connection to the server, the user is to access the app server, so in disguise to achieve the user access to the device.

Instructions for use

TCP Client used as follows:

  1. Related reference library #include <WiFi.h>;
  2. Connect to the Internet (like nonsense) ;
  3. Statement WiFiClientobject is used to connect to the server;
  4. Using the connectmethod of connecting to the server;
  5. Read and write data communication;

Common method

  • int connect(IPAddress ip, uint16_t port)
    int connect(IPAddress ip, uint16_t port, int32_t timeout)
    int connect(const char *host, uint16_t port)
    int connect(const char *host, uint16_t port, int32_t timeout)
    And establish a connection to the server, you can connect to the specified IP address or domain name is specified, the connection is successful return 1, else return 0;
  • size_t write(uint8_t data)
    size_t write(const uint8_t *buf, size_t size)
    size_t write_P(PGM_P buf, size_t size)
    size_t write(Stream &stream)
    Transmission data, returns the number of bytes sent successfully transmitted, else return 0;
    except that write()the outer methods can also be used print()to transmit data or the like;
  • int available()
    Returns the read data length, the data can be read if there is no return 0;
  • int read()
    int read(uint8_t *buf, size_t size)
    Read data from the receive buffer and returns the number of bytes of data to read, if the reading indicates a failure -1, read through the data will be deleted from the reception buffer;
  • int peek()
    Reading the first byte of data, but does not remove it from the reception buffer;
  • void flush()
    Clear the current receive buffer;
  • void stop()
    Close the client, the release of resources;
  • uint8_t connected()
    Returns the current client whether to establish a connection with the server;
  • IPAddress remoteIP() const
    IPAddress remoteIP(int fd) const
    Returns the server IP address;
  • uint16_t remotePort() const
    uint16_t remotePort(int fd) const
    Returns the server port number;
  • IPAddress localIP() const
    IPAddress localIP(int fd) const
    Returns the local IP address;
  • uint16_t localPort() const
    uint16_t localPort(int fd) const
    Returns the local port number;

Basic demo

Tested using the following code:

#include <WiFi.h>

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

const IPAddress serverIP(192,168,50,14); //欲访问的地址
uint16_t serverPort = 50037;         //服务器端口号

WiFiClient client; //声明一个客户端对象,用于与服务器进行连接

void setup()
{
    Serial.begin(115200);
    Serial.println();

    WiFi.mode(WIFI_STA);
    WiFi.setSleep(false); //关闭STA模式下wifi休眠,提高响应速度
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());
}

void loop()
{
    Serial.println("尝试访问服务器");
    if (client.connect(serverIP, serverPort)) //尝试访问目标地址
    {
        Serial.println("访问成功");

        client.print("Hello world!");                    //向服务器发送数据
        while (client.connected() || client.available()) //如果已连接或有收到的未读取的数据
        {
            if (client.available()) //如果有数据可读取
            {
                String line = client.readStringUntil('\n'); //读取数据到换行符
                Serial.print("读取到数据:");
                Serial.println(line);
                client.write(line.c_str()); //将收到的数据回发
            }
        }
        Serial.println("关闭当前连接");
        client.stop(); //关闭客户端
    }
    else
    {
        Serial.println("访问失败");
        client.stop(); //关闭客户端
    }
    delay(5000);
}

Here Insert Picture Description
We figure above TCP Server tools created for testing;

As WEB Client

Tested using the following code:

#include <WiFi.h>

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

const char *host = "www.example.com"; //欲访问的域名

void setup()
{
    Serial.begin(115200);
    Serial.println();

    WiFi.mode(WIFI_STA);
    WiFi.setSleep(false); //关闭STA模式下wifi休眠,提高响应速度
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());
}

void loop()
{
    WiFiClient client; //声明一个客户端对象,用于与服务器进行连接

    Serial.println("尝试访问服务器");
    if (client.connect(host, 80)) //80为一般网站的端口号
    {
        Serial.println("访问成功");

        //向服务器发送请求头,请求网页数据
        //******作为WEB Client使用最核心的就是和WEB Server连接成功后发送相应的请求头请求数据******
        //******WEB Server在收到请求头后返回对应的数据,比如返回网页、图片、文本等******
        //******关于请求头可以参考之前的文章《从零开始的ESP8266探索(06)-使用Server功能搭建Web Server》******
        client.print(String("GET /") + " HTTP/1.1\r\n" +
                     "Host: " + host + "\r\n" +
                     "Connection: close\r\n" +
                     "\r\n");

        //以下代码将收到的网页数据按行打印输出
        //如果是常见的WEB Client(浏览器)的话会将收到的html文件渲染成我们一般看到的网页
        while (client.connected() || client.available()) //如果已连接或有收到的未读取的数据
        {
            if (client.available()) //如果有数据可读取
            {
                String line = client.readStringUntil('\n'); //按行读取数据
                Serial.println(line);
            }
        }

        client.stop(); //关闭当前连接
    }
    else
    {
        Serial.println("访问失败");
        client.stop(); //关闭当前连接
    }
    delay(10000);
}

Here Insert Picture Description
The figure test (though took the previous figures, but the result is the same) we first went to visit www.example.com (the web site is designed for testing), after the success of our connection request to the server to send the request header web page data, the server receives a request to return the head to our response headers and page data (data may refer to the diagram, you can also open the page in a browser and right-click to view source code);
Here Insert Picture Description

TCP Server

Instructions for use

TCP Server used as follows:

  • Related reference library #include <WiFi.h>;
  • Statement WiFiServerobjects;
  • Using the beginmethod starts listening;
  • Listen for client connections and process data communication;

Common method

  • WiFiServer(uint16_t port=80, uint8_t max_clients=4)
    In a statement WiFiServerobject you can choose the number of customers access to the largest port number and enter to listen;
  • WiFiClient available()
    WiFiClient accept(){return available();}
    Try to establish the client object;
  • void begin(uint16_t port=0)
    Server starts listening;
  • void setNoDelay(bool nodelay)
    Set whether the transmission delay (used beginwhen the method is set false, so that the server will send the packets with small data, a time lag);
    open NoDelay response speed can be improved, but in some cases reduces the overall transmission efficiency, it is necessary to set according to the needs of ;
  • bool getNoDelay()
    Returns whether delayed sending;
  • bool hasClient()
    Returns whether there is a client attempts to access;
  • size_t write(const uint8_t *data, size_t len)
    size_t write(uint8_t data){return write(&data, 1);}
    Transmission data, returns the number of bytes sent successfully transmitted, else return 0;
    except that write()the outer methods can also be used print()to transmit data or the like;
  • void end()
    void close()
    void stop()
    Stop the current monitor;
  • int setTimeout(uint32_t seconds)
    Set the timeout;

Basic demo

Tested using the following code:

#include <WiFi.h>

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

WiFiServer server; //声明服务器对象

void setup()
{
    Serial.begin(115200);
    Serial.println();

    WiFi.mode(WIFI_STA);
    WiFi.setSleep(false); //关闭STA模式下wifi休眠,提高响应速度
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected");
    Serial.print("IP Address:");
    Serial.println(WiFi.localIP());

    server.begin(22333); //服务器启动监听端口号22333
}

void loop()
{
    WiFiClient client = server.available(); //尝试建立客户对象
    if (client) //如果当前客户可用
    {
        Serial.println("[Client connected]");
        String readBuff;
        while (client.connected()) //如果客户端处于连接状态
        {
            if (client.available()) //如果有可读数据
            {
                char c = client.read(); //读取一个字节
                                        //也可以用readLine()等其他方法
                readBuff += c;
                if(c == '\r') //接收到回车符
                {
                    client.print("Received: " + readBuff); //向客户端发送
                    Serial.println("Received: " + readBuff); //从串口打印
                    readBuff = "";
                    break; //跳出循环
                }
            }
        }
        client.stop(); //结束当前连接:
        Serial.println("[Client disconnected]");
    }
}

Here Insert Picture Description

As WEB Server

后面会介绍更加方便的WebServer功能,如果想用TCP Server实现这个的话可以参考官方例程:
https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFi/examples/SimpleWiFiServer
或是下面文章:
《从零开始的ESP8266探索(06)-使用Server功能搭建Web Server》

总结

TCP Client与TCP Server的基本使用主要就是上面这些了,结合之前的UDP功能,已经可以开发很多网络应用了。更多内容可以参考如下:
https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFi
另外如果作为客户端使用有安全方面需求可以参考下面连接:
https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFiClientSecure

The WiFiClientSecure class implements support for secure connections using TLS (SSL). It inherits from WiFiClient and thus implements a superset of that class’ interface. There are three ways to establish a secure connection using the WiFiClientSecure class: using a root certificate authority (CA) cert, using a root CA cert plus a client cert and key, and using a pre-shared key (PSK).

Guess you like

Origin blog.csdn.net/Naisu_kun/article/details/87125845