examples: Make tcp_server example support tcp keepalive function

This commit is contained in:
yuanjm 2021-02-03 11:27:06 +08:00 committed by bot
parent fd34406960
commit 94e3141a32
3 changed files with 36 additions and 1 deletions

View File

@ -46,6 +46,12 @@ Set following parameters under Example Configuration Options:
* Set `Port` number of the socket, that server example will create.
* Set `TCP keep-alive idle time(s)` value of TCP keep alive idle time. This time is the time between the last data transmission.
* Set `TCP keep-alive interval time(s)` value of TCP keep alive interval time. This time is the interval time of keepalive probe packets.
* Set `TCP keep-alive packet retry send counts` value of TCP keep alive packet retry send counts. This is the number of retries of the keepalive probe packet.
Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu. See "Establishing Wi-Fi or Ethernet Connection" section in [examples/protocols/README.md](../../README.md) for more details.
## Build and Flash

View File

@ -16,4 +16,21 @@ menu "Example Configuration"
help
Local port the example server will listen on.
config EXAMPLE_KEEPALIVE_IDLE
int "TCP keep-alive idle time(s)"
default 5
help
Keep-alive idle time. In idle time without receiving any data from peer, will send keep-alive probe packet
config EXAMPLE_KEEPALIVE_INTERVAL
int "TCP keep-alive interval time(s)"
default 5
help
Keep-alive probe packet interval time.
config EXAMPLE_KEEPALIVE_COUNT
int "TCP keep-alive packet retry send counts"
default 3
help
Keep-alive probe packet retry count.
endmenu

View File

@ -24,7 +24,10 @@
#include <lwip/netdb.h>
#define PORT CONFIG_EXAMPLE_PORT
#define PORT CONFIG_EXAMPLE_PORT
#define KEEPALIVE_IDLE CONFIG_EXAMPLE_KEEPALIVE_IDLE
#define KEEPALIVE_INTERVAL CONFIG_EXAMPLE_KEEPALIVE_INTERVAL
#define KEEPALIVE_COUNT CONFIG_EXAMPLE_KEEPALIVE_COUNT
static const char *TAG = "example";
@ -62,6 +65,10 @@ static void tcp_server_task(void *pvParameters)
char addr_str[128];
int addr_family = (int)pvParameters;
int ip_protocol = 0;
int keepAlive = 1;
int keepIdle = KEEPALIVE_IDLE;
int keepInterval = KEEPALIVE_INTERVAL;
int keepCount = KEEPALIVE_COUNT;
struct sockaddr_storage dest_addr;
if (addr_family == AF_INET) {
@ -123,6 +130,11 @@ static void tcp_server_task(void *pvParameters)
break;
}
// Set tcp keepalive option
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(int));
setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &keepIdle, sizeof(int));
setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &keepInterval, sizeof(int));
setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &keepCount, sizeof(int));
// Convert ip address to string
if (source_addr.ss_family == PF_INET) {
inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr, addr_str, sizeof(addr_str) - 1);