STM32 ETHERNET #4. TCP SERVER
FIXED the Errors
The code is fixed now and you can receive more than 5 characters without the data being corrupted.
The cubeMX Setup will remain same as the previous Tutorials. I will leave some pictures below for you to refer. For the detailed setup, check out the Connection tutorial
Below are the steps Given to implement the TCP Server with STM32
We will start with the initialization of the TCP server
- Here First of all, we will create a new TCP Control block.
tpcb = tcp_new();
- Then we will bind the Block to the local IP Address and Port. This will be the server IP and Port.
tcp_bind(tpcb, &myIPADDR, 7)
- The next step is to listen for the incoming traffic.
tpcb = tcp_listen(tpcb);
- And finally we will accept the request from the client.
tcp_server_accept initializes few more things. The code for it is shown below
You can see above that it initializes the callbacks like
tcp_arg, tcp_recv and tcp_poll. But here are interested in tcp_recv only.
tcp_recv initializes the callback tcp_server_recv, which will be called whenever the server receives some data from the client. The function is shown below
- Here few things are predefines, and we will leave them as it is. We will focus on line 42 onwards.
- When the data is received for the first time, the state will be set to accepted.
- This is to make sure that the tcp_sent callback is initialized, and it should only initialize once.
- After this, the state will be changed to RECEIVED, and the code at line number 58 will execute.
- here we will store the incoming data into our buffer (line 63), and call the server handle function (line 66) to handle the incoming data.
- I have created this server handle function, so that there you can process the incoming data better. And you should leave the received callback as it is.
Let’s take a look at the server handle function now
- Here we will get the IP address and the port for the client
- The IP address is in the integer format, and we can use the function
ipaddr_ntoato convert the address in the proper format
- The incoming data from the client is stored in the
- I am mixing the incoming data with the new one, and storing it in the buffer.
- Then we will update the
p bufwith the new
payload, total length, and the lengthof the buffer to send.
- Finally we will send the
p bufto the client using
- Here I have used the Hercules as the TCP Client
- The Pink color is the data sent by the client, and in response, the Black color data is sent by the Server
- STM32 Ethernet #12 HTTP Server using AJAX PART2 June 28, 2022
- STM32 Ethernet #11 HTTP Server using AJAX PART1 June 24, 2022
- How to use UART in ESP32 || ESP-IDF June 12, 2022
- Getting started with ESP32 and ESP-IDF || LED Blinking June 5, 2022
- Custom characters in LCD 1602 || STM32 May 25, 2022
- STM32 Ethernet #10 HTTP Server (Basic) using LWIP NETCONN (RTOS) May 18, 2022