Wiznet makers

ronpang

Published July 25, 2025 © Apache License 2.0 (Apache-2.0)

130 UCC

51 WCC

32 VAR

0 Contests

1 Followers

0 Following

Hardwired TCP/IP Chapter 4 :W55MH32 TCP Server Example

Hardwired TCP/IP Chapter 4 :W55MH32 TCP Server Example

COMPONENTS
PROJECT DESCRIPTION

Chapter 4 W55MH32 TCP Server Example

In this article, we will provide a detailed explanation on how to implement TCP communication on the W55MH32 chip. Through practical examples, we will guide you on how to use the W55MH32 as a TCP Server for data loopback testing. For an introduction and characteristics of the TCP protocol, please refer to the TCP Client section.

Other network protocols used in this routine, such as DHCP, can be found in the relevant chapters. Regarding the initialization process of the W55MH32, please refer to the relevant chapters as well. We will not elaborate on this here.

1 Introduction to 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 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 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 take a look at 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 remote servers via Ethernet connections. 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, etc.

Embedded Web server: Some embedded devices have built-in Web servers (such as routers, gateways, sensor devices, etc.), providing web interfaces through the TCP protocol 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 a connection through three handshakes:

  1. The first handshake: The client sends a data packet with the SYN flag to the server, indicating a request to establish a connection.
  2. 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.
  3. 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 disconnected (four-way handshake)

When communication is over, TCP needs to close the connection through four handshakes:

  1. The first wave of farewell: The client sends a FIN data packet, indicating that the data transmission is complete and it is ready to close the connection.
  2. The second wave of farewell: After receiving the FIN data packet, the server replies with an ACK data packet, indicating its consent to close the connection.
  3. The third wave of farewell: The server sends a FIN data packet, indicating that the data transmission is complete and it is ready to close the connection.
  4. The fourth wave of farewell: After receiving the server's FIN data packet, the client sends an ACK data packet, and the connection is officially closed.

IMG_256

TCP Three-way Handshake Diagram

IMG_256

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 a data packet has been successfully received. In TCP communication, each data packet contains a sequence number, and the receiving party uses ACK to inform the sending party of the sequence of bytes that have been successfully received.

  1. 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.
  2. Cumulative Acknowledgment: TCP uses the cumulative acknowledgment method, meaning that the receiver has received all data up to a certain sequence number consecutively.
  3. 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 a lost data packet, 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:

  • Maintain connection status: Check if the remote host is still online to avoid long-term occupation of resources.
  • Release dead connections: If the connection has failed (such as network interruption or the remote host crashing), Keepalive can promptly release resources.
  • Prevent intermediate devices from closing the connection due to timeout: Some NAT, 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 message should be sent after successfully connecting to the server to activate Keepalive.

7 The implementation process

Next, let's take a look at how to implement the TCP server mode on the W55MH32, listen to the port and conduct the loopback test.

Note: The test instance requires that the PC and W55MH32 be on the same network segment.

Step 1: Enable TCP KeepAlive function (to avoid false connection situations)

In W55MH32, the time unit for KeepAlive is 5 seconds. Since we set it to 6 units, that is, to send a KeepAlive message once every 30 seconds.

1.     /* Enable keepalive,Parameter 2 is the keep alive time, with a unit of 5 seconds */
2.     setSn_KPALVTR(SOCKET_ID, 6); // 30s keepalive

Step 2: Run the TCP Server loopback test program within the main loop

1.     while (1)
2.     {
3.         loopback_tcps(SOCKET_ID, ethernet_buf, local_port);
4.     }

The three parameters of the loopback_tcps() function are: SOCKET ID, the communication buffer array, and the local port number.

The example local port number is: 8080.

The content of the loopback_tcps() function is as follows:

 1. /**
 2.  * @brief  tcp server loopback test
 3.  * @param  sn:    socket number
 4.  * @param  buf:   Data sending and receiving cache
 5.  * @param  port:  Listen port
 6.  * @return value for SOCK_ERRORs,return 1:no error
 7.  */
 8. int32_t loopback_tcps(uint8_t sn, uint8_t *buf, uint16_t port)
 9. {
10.     int32_t  ret;
11.     uint16_t size = 0, sentsize = 0;
12.  
13. #ifdef _LOOPBACK_DEBUG_
14.     uint8_t  destip[4];
15.     uint16_t destport;
16. #endif
17.  
18.     switch (getSn_SR(sn))
19.     {
20.     case SOCK_ESTABLISHED:
21.         if (getSn_IR(sn) & Sn_IR_CON)
22.         {
23. #ifdef _LOOPBACK_DEBUG_
24.             getSn_DIPR(sn, destip);
25.             destport = getSn_DPORT(sn);
26.  
27.             printf("%d:Connected - %d.%d.%d.%d : %d\r\n", sn, destip[0], destip[1], destip[2], destip[3], destport);
28. #endif
29. #if KEEPALIVE_ENABLE == 1
30.             // We need to send a packet of data to activate keepalive
31.             ret = send(sn, (uint8_t *)"", 1); // Data send process
32.             if (ret < 0)                      // Send Error occurred (sent data length < 0)
33.             {
34.                 close(sn);                    // socket close
35.                 return ret;
36.             }
37. #endif
38.             setSn_IR(sn, Sn_IR_CON);
39.         }
40.         if ((size = getSn_RX_RSR(sn)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
41.         {
42.             if (size > DATA_BUF_SIZE)
43.                 size = DATA_BUF_SIZE;
44.             ret = recv(sn, buf, size);
45.  
46.             if (ret <= 0)
47.                 return ret; // check SOCKERR_BUSY & SOCKERR_XXX. For showing the occurrence of SOCKERR_BUSY.
48.             size      = (uint16_t)ret;
49.             sentsize  = 0;
50.             buf[size] = 0x00;
51.             printf("rece data:%s\r\n", buf);
52.             while (size != sentsize)
53.             {
54.                 ret = send(sn, buf + sentsize, size - sentsize);
55.                 if (ret < 0)
56.                 {
57.                     close(sn);
58.                     return ret;
59.                 }
60.                 sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
61.             }
62.         }
63.         break;
64.     case SOCK_CLOSE_WAIT:
65. #ifdef _LOOPBACK_DEBUG_
66.         printf("%d:CloseWait\r\n", sn);
67. #endif
68.         if ((ret = disconnect(sn)) != SOCK_OK)
69.             return ret;
70. #ifdef _LOOPBACK_DEBUG_
71.         printf("%d:Socket Closed\r\n", sn);
72. #endif
73.         break;
74.     case SOCK_INIT:
75. #ifdef _LOOPBACK_DEBUG_
76.         printf("%d:Listen, TCP server loopback, port [%d]\r\n", sn, port);
77. #endif
78.         if ((ret = listen(sn)) != SOCK_OK)
79.             return ret;
80.         break;
81.     case SOCK_CLOSED:
82. #ifdef _LOOPBACK_DEBUG_
83.         printf("%d:TCP server loopback start\r\n", sn);
84. #endif
85.         if ((ret = socket(sn, Sn_MR_TCP, port, 0x00)) != sn)
86.             return ret;
87. #ifdef _LOOPBACK_DEBUG_
88.         printf("%d:Socket opened\r\n", sn);
89. #endif
90.         break;
91.     default:
92.         break;
93.     }
94.     return 1;
95. }

In this program, the TCP Server state machine will be executed. Corresponding operations will be performed based on different states of the SOCKET. The state changes of the SOCKET are shown in the following diagram:

IMG_256

  • 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.
  • SOCK_INIT: The SOCKET has been opened successfully. Start listening on the port. When a client connects, the SOCKET state changes to SOCK_ESTABLISHED.
  • SOCK_ESTABLISHED: First, clear the interruption of 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 data from the server, 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 client actively disconnects the connection, the SOCKET state changes to the SOCK_CLOSE_WAIT state. This 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.

8 Run results

After the burning routine is executed, the PHY link detection is carried out first. Then, the network address is obtained through DHCP and the network address information is printed. Finally, the TCP data loopback test is conducted. When the client is not connected, it will continuously listen and wait for the client to connect.

Next, we will open the SocketTester network debugging tool, set it to the TCP Client mode, enter the IP address and port of W55MH32, and then establish a connection. After that, you can see that W55MH32 prints the client connection information. Finally, use SocketTester to send data to W55MH32 for a loopback test.

9 Summary

This article introduces the method of implementing a TCP server mode for data loopback testing on the W55MH32 chip. First, it reviews the relevant knowledge of the TCP protocol, and then presents the implementation process, including enabling the Keepalive function and running the test program in the main loop. The program performs operations based on different states of the SOCKET, which range from closed, initialized, listening, to connection establishment and waiting for closure. After burning the routine, it undergoes PHY link detection, obtains the network address, and completes the test with the help of network debugging tools.

The next article will explain the implementation of UDP communication and data loopback testing on this chip, introducing the relevant principles and implementation steps of UDP. 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, and Asia (excluding South Korea and Japan).

Documents
Comments Write