0

我正在运行基于 LwIP Netconn API 的 tcpecho 示例,代码来自http://www.st.com/web/en/catalog/tools/FM147/CL1794/SC961/SS1743/LN1734/PF257896 特别是描述的 TCP 回显服务器应用程序在应用笔记 UM1713 中,并在文件夹 LwIP_UDPTCP_Echo_Server_Netconn_RTOS 下运行固件,因为我使用的是 FreeRTOS。代码如下。

tcpecho 服务器已经在一个线程上运行,但一次只能处理 1 个客户端,所以我想将其更改为处理多个客户端。据我从不同的论坛读到,解决方案是使用多个线程来处理多个客户端。由于我不是 FreeRTOS 方面的专家,任何人都可以展示如何做到这一点吗?

谢谢,

static void tcpecho_thread(void *arg)
{
  struct netconn *conn, *newconn;
  err_t err, accept_err;
  struct netbuf *buf;
  void *data;
  u16_t len;

LWIP_UNUSED_ARG(arg);

/* Create a new connection identifier. */
conn = netconn_new(NETCONN_TCP);

if (conn!=NULL)
{  
/* Bind connection to well known port number 7. */

err = netconn_bind(conn, NULL, 7);

if (err == ERR_OK)
{
  /* Tell connection to go into listening mode. */
  netconn_listen(conn);

  while (1) 
  {
    /* Grab new connection. */
     accept_err = netconn_accept(conn, &newconn);

    /* Process the new connection. */
    if (accept_err == ERR_OK) 
    {

      while (netconn_recv(newconn, &buf) == ERR_OK) 
      {
        do 
        {
          netbuf_data(buf, &data, &len);
          netconn_write(newconn, data, len, NETCONN_COPY);

        } 
        while (netbuf_next(buf) >= 0);

        netbuf_delete(buf);
      }

      /* Close connection and discard connection identifier. */
      netconn_close(newconn);
      netconn_delete(newconn);
    }
  }
}
else
{
  netconn_delete(newconn);
}
}
}
4

1 回答 1

0

使用以下 API 创建多个线程:

sys_thread_new("TCPECHO", tcp_echoserver_netconn_thread, NULL,
               TCPECHOSERVER_THREAD_STACKSIZE, TCPECHOSERVER_THREAD_PRIO);

在 create new 之后的每个线程中,netconn将其绑定到不同的端口,例如:

  • 在线程 1 ==>err = netconn_bind(conn, NULL, 80);
  • 在线程 2 ==>err = netconn_bind(conn, NULL, 4000);
于 2015-07-04T08:42:22.957 回答