使用 netconn 在同一端口上进行多个连接

使用 netconn 在同一端口上进行多个连接

尝试使用 LwIP 2.0.3 和 FreeRTOS 9.0.0 通过 STM32H743BI 开发 MODBUS 从站应用程序

我的应用程序应该能够同时处理多个客户端。我想为每个接受的连接创建单独的线程,如果不再需要,则终止线程,如下所示:

void modbus_server_netconn_thread(void *arg)
{
  struct netconn *conn = NULL, *newconn = NULL;
  err_t err, accept_err;


  osThreadDef(MBParticular, modbus_handler, osPriorityNormal, 8, configMINIMAL_STACK_SIZE *4);

  /* Create a new TCP connection handle */

  conn = netconn_new(NETCONN_TCP);

  if (conn!= NULL)
  {
    /* Bind to port 502 with default IP address */

    err = netconn_bind(conn, NULL, 502);

    if (err == ERR_OK)
    {
      /* Put the connection into LISTEN state */

      netconn_listen(conn);

      while(1)
      {
        /* accept any incoming connection */

        accept_err = netconn_accept(conn, &newconn);

        if(accept_err == ERR_OK)
        {
            osThreadCreate (osThread(MBParticular), (void *)newconn);

//          /* delete connection */
//          netconn_delete(newconn);  //if I put this here, no data can be rcved
            newconn = NULL;
        }
        else netconn_delete(newconn);
      }
    }
  }
}

static void modbus_handler(void const *arg)
{
  struct netconn *conn = (struct netconn *)arg;
  err_t recv_err;
  u16_t buflen;
  char* buf;
  struct pbuf *p = NULL;
  struct netbuf *inbuf;

  while(TRUE){

  /* Read the data from the port, blocking if nothing yet there.
   We assume the request (the part we care about) is in one netbuf */

  recv_err = netconn_recv(conn, &inbuf);

  if (recv_err == ERR_OK)
  {
    if (netconn_err(conn) == ERR_OK)
    {
      netbuf_data(inbuf, (void**)&buf, &buflen);

    //    HANDLE PACKET

    }
  }

  /* Delete the buffer (netconn_recv gives us ownership, so we have to make sure to deallocate the buffer) */

  netbuf_delete(inbuf);

  }

  /* Close the connection */
  netconn_delete(conn);
  osThreadTerminate(NULL);
}

但不能连接超过 1 个。另一方面,如果 MODBUS Master 程序断开连接,则无法再次连接。在两种情况下,netconn_accept 都会返回 ERR_ABRT。

这是我的 lwipopts.h 的一部分:

#define MEMP_NUM_NETCONN        30
#define MEMP_NUM_NETBUF         30
#define MEMP_NUM_PBUF           60
#define MEMP_NUM_UDP_PCB        6
#define MEMP_NUM_TCP_PCB        10
#define MEMP_NUM_TCP_PCB_LISTEN 8
#define MEMP_NUM_TCP_SEG        8
#define MEMP_NUM_SYS_TIMEOUT    10

我可能会犯一个低级错误。如果这浪费了你的时间,请原谅我。谢谢!

相关内容