Application of TCP/IP protocol based on C# (1)

1. Background and Concept

1. Standard Ethernet

Ethernet was successfully developed by Palo Alto Research Center of Xerox Corporation in 1975, and its core technology originated from ALOHA network. At present, Ethernet refers to the local area network (LAN) product group that conforms to the IEEE 802.3 standard. IEEE 802.3 is a set of Institute of Electrical and Electronics Engineers (IEEE) standards that define the physical layer and data link layer of wired Ethernet media access control , Explains the rules for configuring an Ethernet network and how various network elements cooperate with each other. Ethernet is divided into:
1. Standard Ethernet: The early 10Mbps Ethernet is called Standard Ethernet, which is a bus-type local area network consisting of a coaxial cable and a network card (network adapter). .
Insert picture description here
Sending and receiving data are completed through the CSMA/CD protocol. The process can be briefly summarized as four points: listen first and send, listen while sending, conflict stop, delay retransmission .
2. The bus Ethernet is expanded through repeaters and bridges.
Repeater (Repeater), also called repeater, amplifies the attenuated signal in the transmission medium to increase the transmission distance of the cable.
Bridge, also known as bridge, is a store-and-forward device. It works at the data link layer. When it receives a frame, it first checks the destination MAC address of the frame, and then determines which port the frame is forwarded to.
There are many types of Ethernet, including hub-based Ethernet, switch-based Ethernet, etc., and it has now developed to one hundred thousand Gigabit Ethernet. .

2. Industrial Ethernet

Industrial Ethernet generally means that it is technically compatible with commercial Ethernet (ie IEEE802.3 standard), but in product design, it can meet the requirements of industrial sites in terms of material selection, product strength, applicability, and real-time performance. need.
Currently includes 4 main protocols: HSE, Modbus TCP/IP, ProfINet, Ethernet/IP.
Foundation Fieldbus FF released the Ethernet specification in 2000, called HSE (High Speed ​​Ethernet).
The Modbus TCP/IP protocol was launched by Schneider, which embeds Modbus frames into TCP frames in a very simple way, and combines Modbus with Ethernet and TCP/IP.
Germany's Siemens released the ProfiNet network solution in 2001, which combines the original Profibus with Internet technology. ProfiNet uses standard TCP/IP protocol plus application layer RPC/DCOM to complete communication and network addressing between nodes.
Ethernet/IP is a protocol system suitable for industrial environment applications, based on the CIP (Control and Information Proto-Col) protocol. It is an object-oriented protocol that can ensure the effective transmission of implicit (control) real-time I/O information and explicit information (including configuration, parameter setting, diagnosis, etc.) on the network.
Industrial Ethernet equipment includes the following important parts:
1. Industrial Ethernet hub
2. Industrial Ethernet unmanaged switch
3. Industrial Ethernet managed switch
4. Industrial Ethernet managed redundant switch

3. TCP/IP protocol

Insert picture description here
The above table shows the basic functions and protocols of the network protocol. The TCP (Transmission Control Protocol) protocol is in the transport layer, and the IP (Internet Protocol) protocol is in the network layer.
1. TCP protocol: is a connection-oriented, reliable, byte stream-based transport layer communication protocol. It is a transport protocol specially designed to provide a reliable end-to-end byte stream on an unreliable Internet. . An internetwork is very different from a single network, because different parts of the internetwork may have very different topologies, bandwidths, delays, packet sizes, and other parameters. The design goal of TCP is to be able to dynamically adapt to these characteristics of the Internet and have robustness in the face of various failures.
Insert picture description here
IP protocol
2. IP protocol: It is a protocol for information transfer between networks, which can transfer IP information packets from a source device (such as a user's computer) to a destination device (such as a www server in a certain department). Its purpose is to solve Internet problems and realize the interconnection of large-scale and heterogeneous networks; the other is to separate the coupling relationship between top-level network applications and bottom-level network technologies to facilitate the independent development of the two.
3. Three-way handshake, four-time breakup
Insert picture description here
, SYN: Synchronize Sequence Numbers, which is the handshake signal used when TCP/IP establishes a connection. ACK: ACK (Acknowledge character) is the confirmation character. In data communication, a transmission control character sent by the receiving station to the sending station. Indicates that the data sent has been confirmed to be received correctly.
FIN_WAIT: FIN_WAIT_1 and FIN_WAIT_2 both indicate waiting for each other's FIN message.
4. Sockets The
application layer and the transport layer are separated by sockets. The socket contains two pieces of information: the local port information (local address and port number) connected to the remote, and the remote port information (remote address and port number) connected to the remote.
5. TcpClient and TcpListener.
NET provides these two classes to encapsulate the programming of sockets.
Insert picture description here
Generally, the party that initiates the connection is called the client, and the other is called the server. Now it can be concluded that the server is always using the TcpListener class because it needs to establish an initial connection.

IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener listener = new TcpListener(ip, 8500);

            listener.Start();           // 开始侦听
            Console.WriteLine("Start Listening ...");

Port 8500: Provides HTTP interfaces for obtaining service lists, registration services, and logout services; provides UI services, using cmd:netstat -a;
every time a new TcpClient is created, it is equivalent to creating a new socket Socket to communicate with the server For communication, .Net will automatically assign a port number to this socket.
When creating an instance of the TcpClient type, you can specify the address and port number of the remote server in the constructor. In this way, at the same time as it is created, a connection request ("handshake") will be sent to the remote server. Once it succeeds, the connection between the two is established. You can also use the overloaded parameterless constructor to create an object, and then call the Connect() method, and pass in the remote server address and port number in the Connect() method to establish a connection with the server, no matter if you use a parameterized constructor Connecting to the server, or establishing a connection with the server through the Connect() method, is a synchronous method (or blocking, called block in English).
6. Port communication
After the connection with the server is established, we can send and receive data through this connection. Data is transferred between ports and ports in the form of streams. Because almost any object can be saved in the stream, any type of data can be transferred between the client and the server. For the client, writing data to the stream means transmitting data to the server; reading data from the stream means receiving data from the server. For the server, writing data to the stream means sending data to the client; reading data from the stream means receiving data from the client.

Two, example

1. Establish a connection between the client and the server

Create two console programs respectively.

class Client
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient();
            try
            {
                client.Connect("local", 8500);  
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            Console.WriteLine("Server Connected!{0} --> {1}",client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
        }
    }
static void Main(string[] args)
        {
            Console.WriteLine("Server is running ... ");
            IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener listener = new TcpListener(ip, 8500);
            listener.Start();       
            Console.WriteLine("Start Listening ...");

            TcpClient remoteClient = listener.AcceptTcpClient();
            Console.WriteLine("Client Connected!{0} <-- {1}",remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);                
        }

The result is not displayed, it succeeded anyway, and the two applications established a connection.

2. A client makes multiple requests

static void Main(string[] args)
        {
            const int BufferSize = 8192;    
            Console.WriteLine("Server is running ... ");
            IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener listener = new TcpListener(ip, 8500);
            listener.Start(); 
            Console.WriteLine("Start Listening ...");

            TcpClient remoteClient = listener.AcceptTcpClient();
            Console.WriteLine("Client Connected!{0} <-- {1}",remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);
            NetworkStream streamToClient = remoteClient.GetStream();
            do
            {
                byte[] buffer = new byte[BufferSize];
                int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
                Console.WriteLine("Reading data, {0} bytes ...", bytesRead);

                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: {0}", msg);
            } while (true);
        }
class Client
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Client Running ...");
            TcpClient client;
            try
            {
                client = new TcpClient();
                client.Connect("localhost", 8500);      
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            Console.WriteLine("Server Connected!{0} --> {1}",
                client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
           
            NetworkStream streamToServer = client.GetStream();
            ConsoleKey key;
            Console.WriteLine("Menu: M - Send, G - Exit");
            do
            {
                key = Console.ReadKey(true).Key;

                if (key == ConsoleKey.M)
                {
                    Console.Write("Input the message: ");
                    string msg = Console.ReadLine();

                    byte[] buffer = Encoding.Unicode.GetBytes(msg);    
                    streamToServer.Write(buffer, 0, buffer.Length);  
                    Console.WriteLine("Sent: {0}", msg);
                }
            } while (key != ConsoleKey.G);
            //client.Close();
        }
    }

###3. The server sends back the processed characters
. The server intercepts the character string transmitted by the client and sends it back to the client.

static void Main(string[] args)
        {
            const int BufferSize = 8192;   
            ConsoleKey key;

            Console.WriteLine("Server is running ... ");
            IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            TcpListener listener = new TcpListener(ip, 8500);
            listener.Start();           
            Console.WriteLine("Start Listening ...");

            TcpClient remoteClient = listener.AcceptTcpClient();
            Console.WriteLine("Client Connected!{0} <-- {1}",
                remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);

            NetworkStream streamToClient = remoteClient.GetStream();
            do
            {
                byte[] buffer = new byte[BufferSize];
                int bytesRead;
                try
                {
                    lock (streamToClient)
                    {
                        bytesRead = streamToClient.Read(buffer, 0, BufferSize);
                    }
                    if (bytesRead == 0) throw new Exception("读取到0字节");
                    Console.WriteLine("Reading data, {0} bytes ...", bytesRead);
                    string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Received: {0}", msg);
                    msg = msg.Substring(2);
                    buffer = Encoding.Unicode.GetBytes(msg);
                    lock (streamToClient)
                    {
                        streamToClient.Write(buffer, 0, buffer.Length);
                    }
                    Console.WriteLine("Sent: {0}", msg);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }
            } while (true);

            streamToClient.Dispose();
            remoteClient.Close();

            Console.WriteLine("\n\n输入\"Q\"键退出。");
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
        }
class Client
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Client Running ...");
            TcpClient client;
            ConsoleKey key;
            const int BufferSize = 8192;
            try
            {
                client = new TcpClient();
                client.Connect("localhost", 8500);   
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            Console.WriteLine("Server Connected!{0} --> {1}",
                client.Client.LocalEndPoint, client.Client.RemoteEndPoint);           
            NetworkStream streamToServer = client.GetStream();
            Console.WriteLine("Menu: S - Send, X - Exit");
            do
            {
                key = Console.ReadKey(true).Key;

                if (key == ConsoleKey.S)
                {
                    Console.Write("Input the message: ");
                    string msg = Console.ReadLine();
                    byte[] buffer = Encoding.Unicode.GetBytes(msg);   
                    try
                    {
                        lock (streamToServer)
                        {
                            streamToServer.Write(buffer, 0, buffer.Length);
                        }
                        Console.WriteLine("Sent: {0}", msg);
                        int bytesRead;
                        buffer = new byte[BufferSize];
                        lock (streamToServer)
                        {
                            bytesRead = streamToServer.Read(buffer, 0, BufferSize);
                        }
                        msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                        Console.WriteLine("Received: {0}", msg);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        break;
                    }
                }
            } while (key != ConsoleKey.X);
            streamToServer.Dispose();
            client.Close();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);        
        }
    }

Three, TCP port status description

1.LISTENING status

The FTP (File Transfer Protocol) server stays in this state when it is started, until the connection with the client is successful.

2.ESTABLISHED status

If the connection is successful, it will be in this state, indicating that the two ends are communicating.

3.CLOSE_WAIT state

The other party actively closes the connection or the connection is interrupted due to an abnormal network. It will become this state.

4.TIME_WAIT state

Actively call close() to disconnect, and the status becomes TIME_WAIT after receiving confirmation from the other party. The TCP protocol stipulates that the TIME_WAIT state will continue for 2MSL (twice the maximum lifetime of the segment) to ensure that the old connection state will not affect the new connection.

5.SYN_SENT status

The SYN_SENT state means a connection is requested. When you want to access the services of other computers, you must first send a synchronization signal to the port. At this time, the state is SYN_SENT. If the connection is successful, it will become ESTABLISHED. At this time, the SYN_SENT state is very short. If you find that there are too many SYN_SENTs and are being sent to different machines, the machine may be infected with a virus.

Four, summary

Summarize Socket:
1. Establish a connection between the server and the client.
2. The client sends a message to the server.
3. The server receives the connection from the client.
4. The server processes the message and sends it to the client.
5. The client receives the message.
6. End.

Reference article:
Ethernet
seven-layer network protocol-tcp/ip protocol
network programming

Guess you like

Origin blog.csdn.net/baidu_35536188/article/details/114291257