lwip stack netconn api 保持连接 "keep-alive"

lwip stack netconn api keep connection "keep-alive"

我目前正在使用 lwip 堆栈来实现 modbus 服务器,但是 "keep-alive" 功能不起作用。有人可以看看我的问题吗?

代码:

static void prvweb_ParseHTMLRequest( struct netconn *pxNetCon )
{
struct netbuf *pxRxBuffer;
portCHAR *pcRxString;
unsigned portSHORT usLength;
static unsigned portLONG ulPageHits = 0;

    while(netconn_recv( pxNetCon, &pxRxBuffer) != ERR_OK)
    {
        vTaskDelay( webSHORT_DELAY );
    }
    if( pxRxBuffer != NULL )
    {
        /* Where is the data? */
        netbuf_data( pxRxBuffer, ( void * ) &pcRxString, &usLength );

        if(( NULL != pcRxString               )
        && ( !strncmp( pcRxString, "GET", 3 ) ))
        {
            /********************************* 
                    Generate HTML page 
            *********************************/

            /* Write out the dynamically generated page. */
            netconn_write( pxNetCon, cDynamicPage, (u16_t) strlen( cDynamicPage ), NETCONN_COPY );
        }
        netbuf_delete( pxRxBuffer );
    }

    netconn_close( pxNetCon );
    netconn_delete( pxNetCon );
}

我更改了以下设置:

#ifndef LWIP_TCP_KEEPALIVE
#define LWIP_TCP_KEEPALIVE              1
#endif



#ifndef  TCP_KEEPIDLE_DEFAULT
#define  TCP_KEEPIDLE_DEFAULT     7200000UL /* Default KEEPALIVE timer in milliseconds */
#endif

#ifndef  TCP_KEEPINTVL_DEFAULT
#define  TCP_KEEPINTVL_DEFAULT    75000UL   /* Default Time between KEEPALIVE probes in milliseconds */
#endif

#ifndef  TCP_KEEPCNT_DEFAULT
#define  TCP_KEEPCNT_DEFAULT      9U        /* Default Counter for KEEPALIVE probes */
#endif

我的代码中是否还有其他必须做的事情?如果我尝试这样做,服务器将在传输 HTML 页面后结束连接。我试图删除 netconn_close( pxNetCon ); and/or netconn_delete( pxNetCon ); ,但这不会给出正确的解决方案。连接将保持打开状态,但我无法再次连接。

那么还有其他我没有使用的设置吗?或者是否需要修改代码?

LWIP_TCP_KEEPALIVE 控制编译以支持 TCP keepalive,默认情况下每个连接都关闭 keepalive。

上面的应用程序使用 netconn API 来管理它的连接,没有 netconn API 来启用 SO_KEEPALIVE 选项。为此,您需要使用 LwIP 的 BSD 类套接字 API 和 setsockopt() 调用:

int optval = 1; setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));

如何在 Raw 时启用 Keep-Alive API

  1. 在lwipopts.h
#define LWIP_TCP_KEEPALIVE  1 // enable "kepp-alive"
#define TCP_KEEPIDLE_DEFAULT    1000 // keep_idle : dont' send keep-alive until keep_idle after connecting
#define TCP_KEEPCNT_DEFAULT     9U // keep_cnt : increase when no response after sending keep-alive every keep_intvl
  1. 调用时 tcp_connect(pcb, ...)
pcb->keep_intvl = 1000; // send "keep-alive" every 1000ms
  1. 在循环中()...
if(pcb_client->keep_cnt==pcb_client->keep_cnt_sent)
{
    tcp_client_connection_close(pcb_client, client_s);
}

此设置在服务器拔下后超时 10 秒