Fundamentals of TCP/UDP programming

Posted by boby on Thu, 06 Jan 2022 16:57:41 +0100

1, Brief description of TCP protocol

1. Introduction

Transmission Control Protocol (TCP) is a connection oriented, reliable and byte stream based transport layer communication protocol, which is defined by IETF RFC 793. TCP is designed to adapt to the hierarchical protocol hierarchy supporting multi network applications. Paired processes in host computers connected to different but interconnected computer communication networks rely on TCP to provide reliable communication services. TCP assumes that it can obtain simple and possibly unreliable datagram services from lower level protocols. In principle, TCP should be able to operate on various communication systems connected from hardwired to packet switched or circuit switched networks.

2. Main features

TCP is a wide area network oriented communication protocol, which aims to provide a communication mode between two communication endpoints with the following characteristics when communicating across multiple networks:
(1) Flow based approach;
(2) Connection oriented;
(3) Reliable communication mode;
(4) When the network condition is poor, try to reduce the bandwidth overhead caused by retransmission;
(5) Communication connection maintenance is oriented to two endpoints of communication, regardless of intermediate network segments and nodes. In order to meet these characteristics of TCP protocol, TCP protocol makes the following provisions:
① Data slicing: the user data is sliced at the sending end and reorganized at the receiving end. TCP determines the size of the slicing and controls the slicing and reorganization;
② Arrival confirmation: when the receiving end receives the fragment data, it sends a confirmation to the transmitting end according to the fragment data serial number;
③ Timeout retransmission: the sender starts the timeout timer when sending fragments. If no corresponding confirmation is received after the timer expires, the fragments will be retransmitted;
④ Sliding window: the receiving buffer space of each party of the TCP connection is fixed, and the receiving end only allows the other end to send the data that can be accepted by the buffer of the receiving end. TCP provides flow control on the basis of the sliding window to prevent the buffer overflow of the slower host caused by the faster host;
⑤ Out of order processing: TCP fragments transmitted as IP datagrams may be out of order when they arrive. TCP will reorder the received data and hand over the received data to the application layer in the correct order;
⑥ Repeat processing: the TCP fragments transmitted as IP datagrams will repeat, and the receiving end of TCP must discard the duplicate data; ⑦ Data verification: TCP will maintain the checksum of its header and data, which is an end-to-end checksum to detect any changes in data during transmission. If there is an error in the verification and of the received fragment, TCP will discard the fragment and does not confirm the receipt of the message segment, resulting in the peer timeout and retransmission.

3. Working mode

Establish connection


TCP triple handshake

TCP is a transport layer protocol in the Internet. It uses the triple handshake protocol to establish a connection. When the active party sends a SYN connection request, wait for the other party to answer SYN+ACK, and finally perform ack confirmation on the other party's SYN. This method of establishing connection can prevent wrong connection. The flow control protocol used by TCP is a variable size sliding window protocol.
The process of TCP three handshakes is as follows: the client sends SYN (SEQ=x) message to the server and enters SYN_SEND status. The server receives a SYN message, responds to a SYN (SEQ=y) ack (ACK=x+1) message, and enters SYN_RECV status. The client receives the SYN message from the server, responds to an ACK (ACK=y+1) message, and enters the Established state. After three handshakes, the TCP client and server successfully establish a connection and can start transmitting data.

Connection termination

Termination of TCP connection

Establishing a connection requires three handshakes, while terminating a connection requires four handshakes, which is caused by the half close of TCP. The specific process is shown in the figure below.
(1) An application process first calls close, saying that the end executes "active close". The TCP at this end then sends a FIN segment, indicating that the data has been sent.
(2) The opposite end that receives this FIN executes "passive close", and this FIN is confirmed by TCP. Note: the receipt of FIN is also passed to the receiving end application process as an end of file, after any other data queued for the application process to receive, because the receipt of FIN means that the receiving end application process has no additional data to receive on the corresponding connection.
(3) After a period of time, the application process that receives the file terminator will call close to close its socket. This causes its TCP to also send a FIN.
(4) The original sending end TCP receiving the final FIN (that is, the end performing active shutdown) confirms the FIN.
[3]
Since a FIN and an ACK are required in each direction, four segments are usually required. be careful:
(1) "Usually" means that in some cases, the FIN in step 1 is sent along with the data. In addition, the segments sent in steps 2 and 3 are from the end performing passive shutdown, which may be combined into one segment.
(2) Between step 2 and step 3, it is possible to flow data from the end performing passive closing to the end performing active closing, which is called "half close".
(3) When a Unix process terminates either voluntarily (calling exit or returning from the main function) or involuntarily (receiving a signal to terminate the process), all open descriptors are closed, which also causes a FIN to be issued on any TCP connection that is still open. Either client or server can perform active shutdown. Usually, the client performs active shutdown, but some protocols, such as HTTP/1.0, are performed by the server.

2, UDP protocol overview

1. Introduction

The internet protocol set supports a connectionless transmission protocol called User Datagram Protocol (UDP). UDP provides a method for applications to send encapsulated IP packets without establishing a connection. RFC 768 describes UDP. There are two main protocols in the transport layer of the Internet, which complement each other. Connectionless is UDP, which does little special except to send packets to applications and allow them to architecture their own protocols at the required level. Connection oriented is TCP, which does almost everything.

2. Main features

UDP is a connectionless protocol. Before transmitting data, the source and terminal do not establish a connection. When it wants to transmit, it simply grabs the data from the application and throws it to the network as soon as possible. At the sending end, the speed of UDP data transmission is only limited by the speed of data generated by the application, the ability of the computer and the transmission bandwidth; At the receiving end, UDP puts each message segment in the queue, and the application reads one message segment from the queue at a time.
Since no connection is established for data transmission, there is no need to maintain the connection status, including sending and receiving status. Therefore, one server can transmit the same message to multiple clients at the same time.
The header of UDP packet is very short, only 8 bytes. Compared with the 20 byte packet of TCP, the additional overhead of UDP is very small.
The throughput is not regulated by the congestion control algorithm, but only limited by the data rate generated by the application software, transmission bandwidth, source and terminal host performance.
UDP is message oriented. The UDP of the sender delivers the message handed over by the application to the IP layer after adding the header. It neither splits nor merges, but retains the boundaries of these messages. Therefore, the application needs to select the appropriate message size.
Although UDP is an unreliable protocol, it is an ideal protocol for distributing information. For example, report the stock market on the screen, display aviation information, and so on. UDP is also used to modify routing tables in Routing Information Protocol (RIP). In these applications, if a message is lost, another new message will replace it after a few seconds. UDP is widely used in multimedia applications.

3. Message format

In the UDP protocol hierarchy model, UDP is above the IP layer. The application accesses the UDP layer and then uses the IP layer to transfer packets. The data part of an IP packet is a UDP packet. The header of IP layer indicates the source host and destination host address, while the header of UDP layer indicates the source port and destination port on the host. The segment of UDP transmission consists of an 8-byte header and payload field. The UDP header consists of four domains, each of which occupies 2 bytes, including source port number, target port number, packet length and check value. The UDP datagram format is briefly introduced below
Port number
UDP protocol uses port number to reserve its own data transmission channel for different applications. UDP and TCP protocols use this mechanism to support multiple applications to send and receive data at the same time. The data sender (client or server) sends UDP packets through the source port, while the data receiver receives data through the target port. Some network applications can only use static ports reserved or registered in advance; Other network applications can use unregistered dynamic ports. Because the UDP header uses two bytes to store the port number, the valid range of the port number is from 0 to 65535. Generally speaking, port numbers greater than 49151 represent dynamic ports. There are two ways to specify UDP port number: the management organization specifies the port and dynamic binding.
length
The length of datagram refers to the total number of bytes including header and data part. Because the length of the header is fixed, this field is mainly used to calculate the variable length data part (also known as data load). The maximum length of datagrams varies according to the operating environment. Theoretically, the maximum length of a datagram including a header is 65535 bytes. However, some practical applications often limit the size of datagrams, sometimes down to 8192 bytes.
Check value
UDP protocol uses the check value in the header to ensure the security of data. The check value is first calculated by the data sender through a special algorithm, and needs to be recalculated after it is transmitted to the receiver. If a datagram is tampered with by a third party during transmission or damaged due to line noise, the verification calculation values of the sender and receiver will not match, so UDP protocol can detect whether there is an error. This is different from the TCP protocol, which requires a check value.

Many link layer protocols provide error checking, including popular Ethernet protocols. Maybe you want to know why UDP also provides checking and verification. The reason is that the protocols below the link layer may not provide error detection in some channels between the source and the terminal. Although UDP provides error detection, when an error is detected, UDP does not correct the error, but simply throws away the damaged message segment or provides warning information to the application.

3, Comparison of TCP and UDP protocols

The main difference between UDP and TCP is that they are different in how to realize the reliable transmission of information.
TCP protocol includes a special delivery guarantee mechanism. When the data receiver receives the information from the sender, it will automatically send a confirmation message to the sender; The sender will continue to transmit other information only after receiving the confirmation message, otherwise it will wait until the confirmation message is received. Different from TCP, UDP protocol does not provide a guarantee mechanism for data transmission. If a packet is lost during the transmission from the sender to the receiver, the protocol itself cannot make any detection or prompt. Therefore, UDP protocol is usually called unreliable transmission protocol.
TCP is a connection oriented transmission control protocol, while UDP provides connectionless datagram service; TCP has high reliability to ensure the correctness of transmitted data without loss or disorder; UDP does not establish a connection before transmitting data, does not check and modify datagrams, and does not need to wait for the other party's response. Therefore, packet loss, duplication and disorder will occur. The application program needs to be responsible for all work on transmission reliability; UDP has better real-time performance and higher work efficiency than TCP protocol; UDP segment structure is simpler than TCP segment structure, so the network overhead is also small. TCP protocol can ensure that the receiver can receive the byte stream sent by the sender without error, and provide reliable communication services for applications. Communication systems that require high reliability often use TCP to transmit data.

4, C # programming

1. Write hello word

(1) Create project




(2) Write code

(3) Compile run

(4) Computer intercommunication
① Create a new project clint in a customer service computer (note the introduction of header files. Net and. Net.Sockets)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            //Prompt information
            Console.WriteLine("Press any key to start sending...");
            Console.ReadKey();
            
            int m;

            //Get ready for the link
            UdpClient client = new UdpClient();  //Instance a port
            IPAddress remoteIP = IPAddress.Parse("10.60.202.32");  //Suppose sent to this IP
            int remotePort = 11000;  //Set port number
            IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);  //Instantiate a remote endpoint 

            for(int i = 0; i < 50; i++)
            {
                //Data to send: line n: hello cqjtu! Heavy handed IOT class 2018
                string sendString = null;
                sendString += "The first";
                m = i+1;
                sendString += m.ToString();
                sendString += "that 's ok: hello cqjtu!Heavy handed IOT class 2018";

                //Defines the byte array to send
                //Converts a string to bytes and stores it in a byte array
                byte[] sendData = null;
                sendData = Encoding.Default.GetBytes(sendString);

                client.Send(sendData, sendData.Length, remotePoint);//Send data to remote endpoint 
            }
            client.Close();//Close connection

            //Prompt information
            Console.WriteLine("");
            Console.WriteLine("The data is sent successfully. Press any key to exit...");
            System.Console.ReadKey();
        }
    }
}

② Create a new project server on another server computer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            int result;
            string str = "Line 50: hello cqjtu!Heavy handed IOT class 2018";
            UdpClient client = new UdpClient(11000);
            string receiveString = null;
            byte[] receiveData = null;
            //Instantiate a remote endpoint, IP and port can be specified at will, and call client When receiving (Ref remotepoint), the endpoint will be changed to the real sending endpoint 
            IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
            Console.WriteLine("Preparing to receive data...");
            while (true)
            {
                receiveData = client.Receive(ref remotePoint);//receive data  
                receiveString = Encoding.Default.GetString(receiveData);
                Console.WriteLine(receiveString);
                result = String.Compare(receiveString, str);
                if (result == 0)
                {
                    break;
                }
            }
            client.Close();//Close connection
            Console.WriteLine("");
            Console.WriteLine("After receiving data, press any key to exit...");
            System.Console.ReadKey();
        }
    }
}

③ Compilation results
client


Server


2. Write Form window program

client
(1) Create project


(2) Design From1 interface
Click the toolbox to select two text boxes and a button


Set the properties of the message input box in the lower right corner by yourself

Set button properties by yourself

Set the form properties yourself

Overall display

(3) Write code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
   private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                /*
                 * Displays the current time
                 */
                string str = "The current time: ";
                str += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                textBox2.AppendText(str + Environment.NewLine);
                /*
                 * Prepare for connection
                 */
                int port = 2000;
                string host = "*********";//Server IP address
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);//Convert ip and port to IPEndPoint instance
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//Create a Socket
                /*
                 * Start connection
                 */
                str = "Connect to server...";
                textBox2.AppendText(str + Environment.NewLine);
                c.Connect(ipe);//Connect to server
                /*
                 *send message 
                 */
                string sendStr = textBox1.Text;
                str = "The message content: " + sendStr;
                textBox2.AppendText(str + Environment.NewLine);
                byte[] bs = Encoding.UTF8.GetBytes(sendStr);
                str = "Send the message to the server...";
                textBox2.AppendText(str + Environment.NewLine);
                c.Send(bs, bs.Length, 0);//Send message
                /*
                 * Receive feedback from the server
                 */
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//Receive the returned information from the server
                recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                str = "The server feedback: " + recvStr;//Display server return information
                textBox2.AppendText(str + Environment.NewLine);
                /*
                 * Close socket
                 */
                c.Close();
            }
                 private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                /*
                 * Displays the current time
                 */
                string str = "The current time: ";
                str += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                textBox2.AppendText(str + Environment.NewLine);
                /*
                 * Prepare for connection
                 */
                int port = 2000;
                string host = "*********";//Server IP address
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);//Convert ip and port to IPEndPoint instance
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//Create a Socket
                /*
                 * Start connection
                 */
                str = "Connect to server...";
                textBox2.AppendText(str + Environment.NewLine);
                c.Connect(ipe);//Connect to server
                /*
                 *send message 
                 */
                string sendStr = textBox1.Text;
                str = "The message content: " + sendStr;
                textBox2.AppendText(str + Environment.NewLine);
                byte[] bs = Encoding.UTF8.GetBytes(sendStr);
                str = "Send the message to the server...";
                textBox2.AppendText(str + Environment.NewLine);
                c.Send(bs, bs.Length, 0);//Send message
                /*
                 * Receive feedback from the server
                 */
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//Receive the returned information from the server
                recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                str = "The server feedback: " + recvStr;//Display server return information
                textBox2.AppendText(str + Environment.NewLine);
                /*
                 * Close socket
                 */
                c.Close();
            }

Server
(1) New project (same as client)
(2) Write code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * Prepare for connection
             */
            int i = 0;
            int port = 2000;
            string host = "*******";//ip address
            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//Create a Socket class
            s.Bind(ipe);//Bind 2000 port
            /*
             * Loop listening and processing messages
             */
              while (true)
            {
                i++;
                try
                {
                    Console.Write("Perform operations {0} :",i);
                    Console.WriteLine("\t-----------------------------------------------");
                    s.Listen(0);//Start listening
                    Console.WriteLine("1. Wait for connect...");
                    /*
                     * Instance a new socket port
                     */
                    Socket temp = s.Accept();//Create a new Socket for the new connection.
                    Console.WriteLine("2. Get a connect");
                    /*
                     * Receive the message sent by the client and decode it
                     */
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//Receive information from client
                    recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                    Console.WriteLine("3. Server Get Message:{0}", recvStr);//Display the information from the client
                    /*
                     * Returns the message of successful connection to the client
                     */
                      string sendStr = "Ok!Client send message sucessful!";
                    byte[] bs = Encoding.UTF8.GetBytes(sendStr);
                    temp.Send(bs, bs.Length, 0);//Return client success information
                    /*
                     * Close port
                     */
                    temp.Close();
                    Console.WriteLine("4. Completed...");
                    Console.WriteLine("-----------------------------------------------------------------------");
                    Console.WriteLine("");
                    //s.Close();// Close the socket (since it is in an endless loop again, there is no need to write, but if it is a single receive, the instance socket needs to be closed after completing the task)
                }
                catch (ArgumentNullException e)
                {
                    Console.WriteLine("ArgumentNullException: {0}", e);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException: {0}", e);
                }
            }
        }
    }
}

(3) Compile run
client

Server

5, Summary

Reference connection
https://blog.csdn.net/m0_52869979/article/details/121426319
https://blog.csdn.net/ssj925319/article/details/109336123

Topics: network udp TCP/IP