引言

本文介绍用Select机制在ESP8266上实现一个TCP 并发服务器,对于Select机制的基本使用在上一篇博客已经介绍过了,下面简单讲述一下代码和实验现象:

1.该并发服务器的基本原理是:

(1)在for循环里,通过Select机制,监控可读的文件描述符,若干文件描述符,通过fa_A[]数组维护。

(2)可读的文件描述符分为两类,即已连接的客户端对应的socket描述符发来数据时,该描述符变为可读(对recv()而言“可读”);新建的连接,将触发监听的socket描述符可读(对accept()而言可读)。在for循环里,先处理数据可读、再处理新的连接请求,依此循环检测并处理数据和新连接。

该并发服务器的基本原理构造如下:

ESP32 TCP Socket一直保持连接 esp32 tcp服务器_网络协议

2.代码:

实验用的代码模板是ESP8266 RTOS-SDKv3.3以上版本的Socket TCP Example,开发板是ESP8266DevkitC.

代码中,我尽量添加了注释,帮助理解。

/* BSD Socket API Example
   This example code is in the Public Domain (or CC0 licensed, at your option.)
*/
#include <string.h>
#include <sys/param.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_event.h"
#include "protocol_examples_common.h"
#include "nvs.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>

#define PORT CONFIG_EXAMPLE_PORT

static const char *TAG = "example";

#define BACKLOG 5     // how many pending connections queue will hold
int fd_A[BACKLOG];    // accepted connection fd
int conn_amount;    // current connection amount
#define BUF_SIZE 128

void showclient()
{
    int i;
    printf("client amount: %d\n", conn_amount);
    for (i = 0; i < BACKLOG; i++) {
        printf("[%d]:%d  ", i, fd_A[i]);
    }
    printf("\n\n");
}

static void tcp_server_task(void *pvParameters)
{
    char rx_buffer[BUF_SIZE];
    char addr_str[128];
    int addr_family;
    int ip_protocol;
    fd_set fdsr;
    struct timeval tv;
    conn_amount = 0;
    int i;
    int yes = 1;
    struct sockaddr_in client_addr; // connector's address information
    int maxsockfd;//use for select() to check the readable fd


    while (1) {

#ifdef CONFIG_EXAMPLE_IPV4
        struct sockaddr_in destAddr;
        destAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        destAddr.sin_family = AF_INET;
        destAddr.sin_port = htons(PORT);
        addr_family = AF_INET;
        ip_protocol = IPPROTO_IP;
        inet_ntoa_r(destAddr.sin_addr, addr_str, sizeof(addr_str) - 1);
#else // IPV6
        struct sockaddr_in6 destAddr;
        bzero(&destAddr.sin6_addr.un, sizeof(destAddr.sin6_addr.un));
        destAddr.sin6_family = AF_INET6;
        destAddr.sin6_port = htons(PORT);
        addr_family = AF_INET6;
        ip_protocol = IPPROTO_IPV6;
        inet6_ntoa_r(destAddr.sin6_addr, addr_str, sizeof(addr_str) - 1);
#endif
        /* there are two kinds of sockfd,one is listen_sock,the other is connect_sock*/
        int listen_sock = socket(addr_family, SOCK_STREAM, ip_protocol);
        if (listen_sock < 0) {
            ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket created");
        //allow  socket address reuse
        if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }
        ESP_LOGI(TAG, "address reuse ok");
        int err = bind(listen_sock, (struct sockaddr *)&destAddr, sizeof(destAddr));
        if (err != 0) {
            ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket binded");

        err = listen(listen_sock, BACKLOG);
        if (err != 0) {
            ESP_LOGE(TAG, "Error occured during listen: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket listening");

#ifdef CONFIG_EXAMPLE_IPV6
        struct sockaddr_in6 sourceAddr; // Large enough for both IPv4 or IPv6
#else
        struct sockaddr_in sourceAddr;
#endif
        uint addrLen = sizeof(sourceAddr);
        maxsockfd = listen_sock;//use for select() to check the readable fd

        for (;;)
        {
            // initialize file descriptor set
            FD_ZERO(&fdsr);
            FD_SET(listen_sock, &fdsr);

            // timeout setting
            tv.tv_sec = 60;
            tv.tv_usec = 0;

            // add active connection to fd set
            for (i = 0; i < BACKLOG; i++) {
                if (fd_A[i] != 0) {
                    FD_SET(fd_A[i], &fdsr);
                }
            }
            //block here until listen_sock can read
             int ret = select(maxsockfd+1, &fdsr, NULL, NULL, &tv);
            if (ret < 0) {
                perror("select");
                break;
            } else if (ret == 0) {
                printf("timeout\n");
                continue;
            }
             // check every fd in the set and handle the recv()
            for (i = 0; i < conn_amount; i++) {
                if (FD_ISSET(fd_A[i], &fdsr)) {
                    ret = recv(fd_A[i], rx_buffer, sizeof(rx_buffer) - 1, 0);
                    if (ret <= 0) {        // client close
                        ESP_LOGE(TAG, "recv failed or connection closed: errno %d", errno);
                        printf("client[%d] close\n", i);
                        close(fd_A[i]);
                        FD_CLR(fd_A[i], &fdsr);
                        fd_A[i] = 0;
                    } else {        // receive data                        
                        if (ret < BUF_SIZE)
                            memset(&rx_buffer[ret], '\0', 1);
                        printf("client[%d] send:%s\n", i, rx_buffer);
                        int err = send(fd_A[i], rx_buffer, ret, 0);
                        if (err < 0) {
                        ESP_LOGE(TAG, "Error occured during sending: errno %d", errno);
                        continue;
                        }
                    }
                }
            }

            // check whether a new connection comes and handler the new connection
            if (FD_ISSET(listen_sock, &fdsr)) {
                int connect_sock = accept(listen_sock, (struct sockaddr *)&client_addr, &addrLen);
                if (connect_sock <= 0) {
                    perror("accept");
                    continue;
                }
                ESP_LOGI(TAG, "Socket accepted");

                // add to fd queue
                if (conn_amount < BACKLOG) {
                    fd_A[conn_amount++] = connect_sock;
                    printf("new connection client[%d] %s:%d\n", conn_amount,
                            inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                    if (connect_sock > maxsockfd)
                        maxsockfd = connect_sock;
                }
                else {
                    printf("max connections arrive, exit\n");
                    send(connect_sock, "bye", 4, 0);
                    close(connect_sock);
                    continue;
                }
            }
            showclient();
        }
         //  when select() return error, close other connections
        for (i = 0; i < BACKLOG; i++) {
            ESP_LOGE(TAG, "Shutting down socket and restarting...");
            if (fd_A[i] != 0) {
                shutdown(fd_A[i], 0);
                close(fd_A[i]);
            }
        }
    }
    vTaskDelete(NULL);
}

void app_main()
{
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    ESP_ERROR_CHECK(example_connect());

    xTaskCreate(tcp_server_task, "tcp_server", 4096, NULL, 5, NULL);
}

3.实验现象与分析:

(1)开发板编译烧录上述程序后,打印信息如下,首先开发板运行的TCP Server进入Listen状态(即监听状态):

ESP32 TCP Socket一直保持连接 esp32 tcp服务器_freertos_02

在代码中,我们通过tv.tv_sec = 60;语句将select()的超时时间设置为60秒,即select将监控60s内可读的文件描述符,超过60秒若无可读文件描述符,就触发超时异常,程序终止。

所以让我们打开终端,输入以下命令,运行一个模拟的TCP Client,连接我们的TCP Server:

nc  192.168.47.104  3333

(注意根据你的上图中的串口打印信息,替换命令中的IP地址,对nc命令以及TCP Server/Client不了解的可以参考我的博客Socket编程(1))

ESP32 TCP Socket一直保持连接 esp32 tcp服务器_freertos_03

连接后,向开放板上的TCP Server发出消息“you got me",则开发板也会回复一条同样的消息“you got me"。此时,开发板对应的串口输出信息如下:

ESP32 TCP Socket一直保持连接 esp32 tcp服务器_网络协议_04

即接收客户端client[1]的连接, 当前连接的client[1]在服务器中对应的文件描述符为55,收到client[1]的消息后,发送同样的消息“you got me"给客户端。同时,统计当前已经连接的客户端的数量为1。

(2)让我们再打开一个新的终端(原终端不要关闭),执行同样的命令:nc  192.168.47.104  3333,并发送消息“ha ha"

如下:

ESP32 TCP Socket一直保持连接 esp32 tcp服务器_网络协议_05

同样的,开发板也会回复一条同样的消息“ha ha"。此时,开发板对应的串口输出信息如下:

ESP32 TCP Socket一直保持连接 esp32 tcp服务器_socket_06

接收一个新连接client[2],当前已连接状况是fd为55的client[1],以及fd为56的client[2].接收到client[2]发送的消息“ha ha",并将接收的消息再发送给client[2]。当前已经连接的client 数量已经变为2.

此时,并发服务器的测试已经完成了,你可以再打开几个终端,运行nc  192.168.47.104  3333命令,建立新的客户端与开发板上的TCP Server进行连接与消息交互。

你看,我们的开发板上的TCP Server,可以同时处理好几个PC端模拟的TCP Client的连接和数据收发:

ESP32 TCP Socket一直保持连接 esp32 tcp服务器_socket_07

目前实现的这个TCP并发服务器还有很多可以优化改进的地方,如果有疑问或者改进的建议,欢迎留言讨论。