Q: How to create threads in FreeRTOS to handle multiple Clients on a TCP Server using LwIP Netconn API?

2.4k views Asked by At

I am running the tcpecho sample based on LwIP Netconn API, code from http://www.st.com/web/en/catalog/tools/FM147/CL1794/SC961/SS1743/LN1734/PF257896 particularly the TCP echo server application described at the application note UM1713, and running the firmware under folder LwIP_UDPTCP_Echo_Server_Netconn_RTOS since I am using FreeRTOS. Code is below.

The tcpecho server is already running on a thread, but can only handle 1 Client at time, so I would like to change it to handle multiple Clients. As far I read from different forums, the solution would be using multiple threads to handle multiple Clients. Since I am not a expert in FreeRTOS, can anyone show how this can be done?

Thanks,

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);
}
}
}
1

There are 1 answers

2
Mohsin On

Create multiple threads by using the following API:

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

In each thread after the create new netconn bind it to a different port, for eg.:

  • In thread 1 ==> err = netconn_bind(conn, NULL, 80);
  • In thread 2 ==> err = netconn_bind(conn, NULL, 4000);