How to establish TCP client's limit in tcp server socket in ESP32?

MiguelBailonS
Posts: 4
Joined: Thu Aug 05, 2021 10:38 pm

How to establish TCP client's limit in tcp server socket in ESP32?

Postby MiguelBailonS » Thu Aug 05, 2021 10:41 pm

Hi,
I am using lwip/sockets.h library to create a TCP Server
to handle just one TCP client connection.
In listen() function I set the amount of TCP clients in queue to
to 0.
But, when I initiate the TCP Server, and try to connect with two TCP clients
at the same time with hercules TCP Client, I get both of them connected to my
TCP Server.

How can I handle this event to just get one of them connected?

I am using an freeRTOS task to set up my TCP server, and then
in the while loop, i used the blocking function: accept().
The while loop doesnt have a delay to execute, but even with a delay
it doesnt work the way I want.

Thank you for your time.

ESP_Sprite
Posts: 9746
Joined: Thu Nov 26, 2015 4:08 am

Re: How to establish TCP client's limit in tcp server socket in ESP32?

Postby ESP_Sprite » Fri Aug 06, 2021 2:02 am

Your capslock seems to have been accidentally stuck on while typing the title of this topic. I took the liberty to correct that for you. Also, can you post your code somewhere? Your description isn't super clear.

MiguelBailonS
Posts: 4
Joined: Thu Aug 05, 2021 10:38 pm

Re: How to establish TCP client's limit in tcp server socket in ESP32?

Postby MiguelBailonS » Fri Aug 06, 2021 2:11 pm

  1.     err = listen(listen_sock, 1); // listen() function
  2.     if (err != 0) {
  3.         ESP_LOGE(TAG, "Error occurred during listen: errno %d", errno);
  4.         goto CLEAN_UP;
  5.     }
  6.  
  7.     while (1) { // while of freeRTOS task without delay
  8.         struct sockaddr_storage source_addr; // Large enough for both IPv4 or IPv6
  9.         uint addr_len = sizeof(source_addr);
  10.         int sock = accept(listen_sock, (struct sockaddr *)&source_addr, &addr_len);
  11.         if (sock < 0) {
  12.             ESP_LOGE(TAG, "Unable to accept connection: errno %d", errno);
  13.             break;
  14.         }
  15.  
  16.         // Convert ip address to string
  17.         if (source_addr.ss_family == PF_INET) {
  18.             inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr, addr_str, sizeof(addr_str) - 1);
  19.         } else if (source_addr.ss_family == PF_INET6) {
  20.             inet6_ntoa_r(((struct sockaddr_in6 *)&source_addr)->sin6_addr, addr_str, sizeof(addr_str) - 1);
  21.         }
  22.         ESP_LOGI(TAG, "Socket accepted ip address: %s", addr_str);
  23.         do_retransmit(sock);
  24.        
  25.         shutdown(sock, 0);
  26.         close(sock);
  27.     }
  28.  
  29. CLEAN_UP:
  30.     close(listen_sock);
  31.     vTaskDelete(NULL);
  32. }
Here is the code, thanks for your correction.

Who is online

Users browsing this forum: Baidu [Spider], BipinDangwal, Google [Bot], MicroController and 111 guests