1. 程式人生 > >(轉)lwip TCP client & FreeRTOS 開啟TCP 的 保活機制 LWIP_TCP_KEEPALIVE==1

(轉)lwip TCP client & FreeRTOS 開啟TCP 的 保活機制 LWIP_TCP_KEEPALIVE==1

參考大神教程:http://blog.sina.com.cn/s/blog_62a85b950101aw8x.html   老衲五木

      :http://blog.sina.com.cn/s/blog_62a85b950102vrr4.html     老衲五木

      :http://blog.csdn.net/zhzht19861011/article/details/46564699 朱工

 

第一步:在opt.h中 LWIP_TCP_KEEPALIVE  置1

1 /**
2  * LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT
3 * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set 4 * in seconds. (does not require sockets.c, and will affect tcp.c) 5 */ 6 #if !defined LWIP_TCP_KEEPALIVE || defined __DOXYGEN__ 7 #define LWIP_TCP_KEEPALIVE 1 8 #endif

第二步:在lwipopts.h檔案中新增 四個巨集定義

1 #define  TCP_KEEPIDLE_DEFAULT     5000UL       // 5秒內連線雙方都無資料,則發起保活探測(該值預設為2小時)
2 #define  TCP_KEEPINTVL_DEFAULT    1000UL         // 每1秒傳送一次保活探測
3 //保活機制啟動後,一共傳送5次保活探測包,如果這5個包對方均無迴應,則表示連線異常,核心關閉連線,併發送err回撥到使用者程式
4 #define  TCP_KEEPCNT_DEFAULT      5UL               
5 #define  TCP_MAXIDLE  TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT

第三步:因為 我 做的 是 TCP client ,協議棧不預設開啟保活機制,因此需要開啟。這裡一定 要在   conn = netconn_new(NETCONN_TCP); 這句程式碼之後進行 設定否則 造成記憶體錯誤啊 。。

1 /* Create a new connection identifier. */
2                 conn = netconn_new(NETCONN_TCP);
3                 
4                 if (conn!=NULL)
5                 {
6                         
7                     //開啟TCP 的保活功能 (客戶端不預設開啟)
8                     conn->pcb.tcp->so_options |= SOF_KEEPALIVE;//SOF_KEEPALIVE=0x08U

第四步:編譯發現不能通過,需要包含兩個標頭檔案

1 #include "lwip/tcp.h"
2 #include "lwip/ip.h"

 

部落格轉自:https://www.cnblogs.com/suozhang/p/6743479.html