Hardwired TCP/IP Chapter 24: W55MH32TCP_Client_Multi_Socket Example
Hardwired TCP/IP Chapter 24: W55MH32TCP_Client_Multi_Socket Example

Hardwired TCP/IP Chapter 24: W55MH32TCP_Client_Multi_Socket Example
In this article, we will provide a detailed explanation on how to implement TCP communication on the W55MH32 chip. By using the TOE engine of W55MH32, we only need to perform simple socket programming and register reading and writing, and we can easily implement TCP protocol applications. Next, through practical examples, we will explain to you how to use the 8 sockets on the TOE engine, set them to TCP Client mode, and simultaneously connect to a server for data loopback testing.
Other network protocols used in this routine, such as DHCP, please refer to the relevant sections. Regarding the initialization process of W55MH32, please refer to the Network Install section. We will not elaborate on this here.
1 Introduction to the TCP Protocol
TCP (Transmission Control Protocol) is a connection-oriented and reliable transport layer protocol, which is used to reliably transmit data over the network. TCP is one of the core protocols in the Internet protocol family and is usually used together with the IP protocol (Internet Protocol) to form socket communication.
2 Characteristics of the TCP Protocol
- Connection-oriented: Before transmitting data, TCP needs to establish a connection to ensure that the sender and the receiver can communicate with each other. The connection is established through the Three-Way Handshake process, ensuring reliable communication between the two parties.
- Reliability: TCP provides reliable data transmission, ensuring that the data is complete and arrives at the receiving end in order. If data is lost or corrupted, TCP will automatically retransmit the lost data packets.
- Flow Control: TCP uses a flow control mechanism to regulate the speed of data transmission, preventing the receiving end from being overwhelmed and resulting in data loss. The commonly used flow control method is Sliding Window.
- Congestion Control: TCP can dynamically adjust the transmission rate to avoid network congestion. Algorithms such as Slow Start, Congestion Avoidance, and Fast Retransmission are adopted.
- Full-duplex Communication: After the TCP connection is established, data can be transmitted simultaneously in both directions, supporting two-way communication.
- Ordered Data Transmission: TCP numbers the data packets to ensure that the data is transmitted in order, even if there is network delay, the receiving end can receive the data in order.
- Byte Stream Service: The data transmitted by TCP is a byte stream, it does not care about the boundaries of the application layer data, and the application layer needs to parse the data boundaries itself.
3 The differences between TCP and UDP
TCP is a reliable, connection-oriented protocol, suitable for applications that require data integrity and sequence guarantee, such as web browsing and file transfer.
UDP (User Datagram Protocol) is a connectionless, unreliable protocol, suitable for applications that have high requirements for timeliness and can tolerate packet loss, such as video streaming and online games.
4 TCP application scenarios
Next, let's explore what operations and applications can be accomplished using the TCP protocol on the W55MH32?
- Remote monitoring and data collection: Embedded devices are typically used to collect sensor data and upload it to a remote server via Ethernet. The TCP protocol ensures the reliability and integrity of data transmission.
- Remote device control: Many embedded systems need to receive control instructions over the network (such as PLC control in industrial automation), and the TCP protocol provides a reliable communication channel.
- Internet of Things (IoT): Many IoT devices use the TCP protocol to communicate with cloud servers or other devices, transmitting data, executing commands, and so on.
- Embedded Web server: Some embedded devices have built-in Web servers (such as routers, gateways, sensor devices, etc.), and through the TCP protocol, they provide web interfaces for users to configure and monitor.
5 The process of conducting data interaction using TCP
TCP connection establishment (three-way handshake)
Before starting to transmit data, TCP will establish the connection through three handshakes:
- The first handshake: The client sends a data packet with the SYN flag to the server, indicating a request to establish a connection.
- The second handshake: After receiving the SYN packet, the server replies with a data packet containing the SYN and ACK flags, indicating its consent to establish the connection.
- The third handshake: After receiving the SYN+ACK from the server, the client sends a data packet with the ACK flag, completing the connection establishment.
Data interaction
TCP connection is closed (four-way handshake)
When communication ends, TCP needs to close the connection through four-way handshakes:
- The first wave of handover: The client sends a FIN data packet, indicating that the data transmission is complete and it is ready to close the connection.
- The second wave of handover: After receiving the FIN data packet, the server replies with an ACK data packet, indicating its consent to close the connection.
- The third wave of handover: The server sends a FIN data packet, indicating that the data transmission is complete and it is ready to close the connection.
- The fourth wave of handover: After receiving the server's FIN data packet, the client sends an ACK data packet, and the connection is officially closed.
TCP Three-way Handshake Diagram
TCP Four-way Handshake Diagram
6 The ACK mechanism, retransmission mechanism and Keepalive mechanism of TCP
The ACK mechanism of TCP
ACK is the mechanism used by TCP to confirm that data packets have been successfully received. In TCP communication, each data packet contains a sequence number, and the receiver uses ACK to inform the sender of the sequence of bytes that have been successfully received.
- ACK field: The ACK is included in the TCP header and indicates the sequence number of the next byte that the receiver expects to receive.
- Cumulative Acknowledgment: TCP uses the cumulative acknowledgment method, meaning that the receiver has received all data up to a certain sequence number consecutively.
- Timeout Retransmission: If the sender does not receive an ACK within the timeout period, it will retransmit the data packet.
The retransmission mechanism of TCP
The retransmission mechanism of TCP ensures the reliable transmission of data. The following are common retransmission mechanisms:
- Timeout retransmission::
- The sender sets a timer. If the sent data packet does not receive an ACK within the specified time, it triggers a retransmission.
- The timeout period is dynamically adjusted and is estimated based on the round-trip time (RTT) of TCP.
- Fast retransmission:
- When the receiving party detects that a data packet has been lost, it sends a duplicate ACK (referred to as a redundant ACK) to alert the sender that a certain data packet has not arrived.
- If the sender receives three consecutive duplicate ACKs, it will immediately retransmit the corresponding data packet without waiting for a timeout.
- Selective Retransmission (Selective Repeat, SACK):
- Based on the cumulative confirmation, TCP can also inform the sender through the SACK option which specific blocks have been received and which ones have not.
- This can reduce unnecessary retransmissions and improve efficiency.
TCP Keepalive mechanism
TCP Keepalive is an optional mechanism of the TCP protocol, used to detect whether a long-idle connection is still valid. Its main function is:
1. Maintain connection status: Check if the remote host is still online to avoid long-term occupation of resources.
2. Release dead connections: If the connection has failed (such as network interruption or the remote host crashing), Keepalive can promptly release resources.
3. Prevent intermediate devices from closing the connection due to timeout: Some NATs, routers, or firewalls may automatically close the connection when it remains inactive for a long time. Keepalive can prevent this situation.
Usage: In the TOE engine of W55MH32, the Keepalive time needs to be set in the Sn_KPALVTR register, and then a data packet should be sent after successfully connecting to the server to activate Keepalive.
7 The implementation process
Next, let's see how to implement simultaneous opening of 8 sockets for loopback testing in the code.
Note: The test instance requires that the PC and W55MH32 be on the same network segment.
First, the multi_tcpc_socket() function needs to be called in the main function.
1. while (1)
2. {
3. multi_tcpc_socket(ethernet_buf, dest_ip, dest_port);
4. }
The multi_tcpc_socket() function has three parameters: ethernet_buf serves as the data buffer for data transmission between the client and the server.
dest_ip represents the IP address of the target server. dest_port is the port number of the target server.
The content of the multi_tcpc_socket() function is as follows:
1. int32_t multi_tcpc_socket(uint8_t *buf, uint8_t *destip, uint16_t destport)
2. {
3. int32_t ret; // return value for SOCK_ERRORs
4. uint16_t size = 0, sentsize = 0;
5. // Socket Status Transitions
6. // Check the W5500 Socket n status register (Sn_SR, The 'Sn_SR' controlled by Sn_CR command or Packet send/recv status)
7. switch (getSn_SR(socket_sn))
8. {
9. case SOCK_ESTABLISHED:
10. if (getSn_IR(socket_sn) & Sn_IR_CON) // Socket n interrupt register mask; TCP CON interrupt = connection with peer is successful
11. {
12. #ifdef _LOOPBACK_DEBUG_
13. printf("%d:Connected to - %d.%d.%d.%d : %d\r\n", socket_sn, destip[0], destip[1], destip[2], destip[3], destport);
14. #endif
15. setSn_IR(socket_sn, Sn_IR_CON); // this interrupt should be write the bit cleared to '1'
16. }
17. //////////////////////////////////////////////////////////////////////////////////////////////
18. // Data Transaction Parts; Handle the [data receive and send] process
19. //////////////////////////////////////////////////////////////////////////////////////////////
20. if ((size = getSn_RX_RSR(socket_sn)) > 0) // Sn_RX_RSR: Socket n Received Size Register, Receiving data length
21. {
22. if (size > DATA_BUF_SIZE)
23. size = DATA_BUF_SIZE; // DATA_BUF_SIZE means user defined buffer size (array)
24. ret = recv(socket_sn, buf, size); // Data Receive process (H/W Rx socket buffer -> User's buffer)
25. buf[size] = 0x00;
26. printf("%d:rece from %d.%d.%d.%d:%d data:%s\r\n", socket_sn, destip[0], destip[1], destip[2], destip[3], destport, buf);
27. if (ret <= 0)
28. return ret; // If the received data length <= 0, receive failed and process end
29. size = (uint16_t)ret;
30. sentsize = 0;
31.
32. // Data sentsize control
33. while (size != sentsize)
34. {
35. ret = send(socket_sn, buf + sentsize, size - sentsize); // Data send process (User's buffer -> Destination through H/W Tx socket buffer)
36. if (ret < 0) // Send Error occurred (sent data length < 0)
37. {
38. close(socket_sn); // socket close
39. return ret;
40. }
41. sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
42. }
43. }
44. //////////////////////////////////////////////////////////////////////////////////////////////
45. break;
46. case SOCK_CLOSE_WAIT:
47. #ifdef _LOOPBACK_DEBUG_
48. printf("%d:CloseWait\r\n", socket_sn);
49. #endif
50. if ((ret = disconnect(socket_sn)) != SOCK_OK)
51. return ret;
52. #ifdef _LOOPBACK_DEBUG_
53. printf("%d:Socket Closed\r\n", socket_sn);
54. #endif
55. break;
56. case SOCK_INIT:
57. #ifdef _LOOPBACK_DEBUG_
58. printf("%d:Try to connect to the %d.%d.%d.%d : %d\r\n", socket_sn, destip[0], destip[1], destip[2], destip[3], destport);
59. #endif
60. if ((ret = connect(socket_sn, destip, destport)) != SOCK_OK)
61. return ret; // Try to TCP connect to the TCP server (destination)
62. break;
63. case SOCK_CLOSED:
64. close(socket_sn);
65. if ((ret = socket(socket_sn, Sn_MR_TCP, any_port++, 0x00)) != socket_sn)
66. {
67. if (any_port == 0xffff)
68. any_port = 50000;
69. return ret; // TCP socket open with 'any_port' port number
70. }
71. #ifdef _LOOPBACK_DEBUG_
72. printf("%d:TCP client loopback start\r\n", socket_sn);
73. printf("%d:Socket opened\r\n", socket_sn);
74.
75. #endif
76. break;
77. default:
78. break;
79. }
80.
81. if (socket_sn < _WIZCHIP_SOCK_NUM_)
82. {
83. socket_sn++;
84. }
85. else
86. {
87. socket_sn = 0;
88. }
89. return 1;
90. }
In this function, a TCP Client state machine will be executed. Corresponding operations will be performed based on the different states of the SOCKET. The state changes of the SOCKET are as shown in the following figure:
- SOCK_CLOSED: The current SOCKET is not open. After configuring the connection to the server and the port number, open the SOCKET. Once the SOCKET is opened successfully, it will enter the SOCK_INIT state.
- Note: Because when the W55MH32 abnormally disconnects from the server, the server does not know that we have disconnected, so when using the previous connection port to continue the connection, the server will reject the connection. Therefore, in this case, after a connection failure, we will automatically increment the connection port by 1 to solve the problem of failed reconnection. If in some specific scenarios, the server only allows the client to connect using a fixed port, then this operation of automatically incrementing the connection port cannot be used here.
- SOCK_INIT: The SOCKET performs the operation of connecting to the server. If the connection is successful, the SOCKET state changes to SOCK_ESTABLISHED; if the connection fails, the SOCKET state changes to the closed state.
- SOCK_ESTABLISHED: First, clear the interruption of the successful connection and send 1 packet of data to activate KeepAlive. Then read the value of the Sn_RX_RSR (idle receive buffer register) register. When receiving server data, the value of the Sn_RX_RSR register will be greater than 0. At this time, we will print the received data and send the data in a loop.
- SOCK_CLOSE_WAIT: When the server actively disconnects the connection, the SOCKET state changes to the SOCK_CLOSE_WAIT state, which is a semi-closed state, allowing for the final data transmission before closing. When using the disconnect() function to completely disconnect the connection, the SOCKET state will change to the SOCK_CLOSED state.
After executing the state machine, it will automatically switch to the next socket, enabling the simultaneous opening of 8 sockets for TCP Client mode data loopback testing.
8 Run results
After the burning routine is executed, it first conducts a PHY link detection, then prints the set network address information, and finally performs a TCP_Client_Multi_Socket data loopback test. When the server is not enabled, it will continuously print the prompts for opening the socket and connecting to the server.
9 Summary
This article explains how to use 8 sockets on the W55MH32 chip to implement the TCP client mode, and simultaneously connect to 1 server for data loopback testing. Through practical examples, it demonstrates the complete process from initializing the socket to establishing the connection, data interaction, and handling connection closure. The article details the concept, characteristics, differences from UDP, application scenarios, data interaction process, ACK mechanism, retransmission mechanism, and Keepalive mechanism of the TCP protocol, helping readers understand its practical application value in reliable data transmission.
The next article will explain how to implement multiple Socket settings as TCP server mode on the W55MH32 and listen to the same port for testing. It will analyze the core principle and application of this function, as well as explain the specific steps and key points for implementing this function on the W55MH32. Stay tuned!
WIZnet is a non-chipfoundry semiconductor company founded in 1998. Its products include the Internet processor iMCU™, which adopts TOE (TCP/IP Offloading Engine) technology and is based on a unique patented fully hardwired TCP/IP. iMCU™ is designed for embedded Internet devices in various applications.
WIZnet has over 70 distributors worldwide, with offices in Hong Kong, South Korea, and the United States, providing technical support and product marketing.
The region managed by the Hong Kong office includes: Australia, India, Turkey, Asia (excluding South Korea and Japan).