SoFunction
Updated on 2025-03-07

C# UDP network communication implementation example

Basic concepts of TCP and UDP

TCP:(Transmission Control Protocol) is a connection-oriented, reliable, byte stream-based transport layer communication protocol. It also provides full duplex communication, allowing two applications to directly establish a reliable connection for data exchange/UDP: (User Datagram Protocol): is a connectionless, unreliable, data packet transmission layer protocol, which does not provide packets of data packets. The sorting and assembly functions do not provide a guarantee of reliability.

The difference between TCP and UDP

It is based on connections and udp is based on non-connections

Transmission data is stable and reliable, suitable for scenarios with high requirements for network communication quality, and needs to be sent to the other party accurately. For example, transfer files, send emails, browse web pages

The advantages are fast and lightweight. However, packet loss may occur, so it is suitable for scenarios where real-time requirements are high but there is no high requirement for packet loss, such as domain name query, voice call, live video, etc.

Features of UDP protocol

Simple protocol based on IP, unreliable protocol

2. The advantages are simplicity, lightweight, high transmission speed, and low reliability requirements

3.shortcoming:No flow control,No response confirmation mechanism。 Cannot solve the problem of packet loss and resending incorrect order

UDP usage scenarios

When the application does not require high transmission reliability but has high transmission speed and latency requirements. For example, voice and video chat. Mainly in these scenarios, if one or two packets are lost, it will not have much impact.

UDP Server

Controls

Two buttons (open server button, send message button), input box, text box control (RichTextBox: Show chat)

Open Server Button Method

Create global variables Socket

 // Let's talk about socket first to write client and server Socket socket;
 private void button1_Click(object sender, EventArgs e)
 {
     // Parameter 1 ip address type ipv4 type     //Parameter 2 Passing data type Data message type     //Parameter 3 Protocol type udp protocol     //1 Create socket as server object     socket = new Socket(, , );
     // 2 binding ip and port     IPAddress iPAddress = ("192.168.107.83");
     (new IPEndPoint(iPAddress,8081));
     //3 Accept the message     startReceive();
 }
    void startReceive()
  {
      //Create a thread and start the thread      new Thread(() =>
      {
          byte[] body = new byte[1024];
          while (true)
          {
              
              int count =   (body); // Accept data              string s = Encoding.(body, 0, count);
              ((Action)(() =>
              {
                  (s + "\t\n");
                  =;
                  ();
              }));
          }

      }).Start() ;
  }    

Send message event

//Methods to send messages to the specified personstring[] ips = new string[] {"192.168.107.83",  };
private void button2_Click(object sender, EventArgs e)
{
    (Encoding.(this.),
        new IPEndPoint(("192.168.107.83"), 8082)
        );
}

UDP Client

Controls

Three buttons (on, send, close), RichTextBox (show chat)

        public Form1()
        {
            InitializeComponent();
            
        }
        void f1()
        {
            byte[] body = new byte[1024];
            while (true)
            {
                int count = (body); // Accept data                string s = Encoding.(body, 0, count);
                ((Action)(() =>
                {
                    (s + "\t\n");
                     = ;
                    ();
                }));
            }
        }
        // Open the connection        Socket socket;
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //1Create a client object                socket = new Socket(, , );
                //bind If the ports written by the front and back ends are consistent, an error occurs, and the port number can only be used once                //2 Bind ip and port number               (new IPEndPoint(("192.168.107.83"), 8082));
                Thread th = new Thread(f1);
                ();
            }
            catch (Exception ex)
            {
                ("Port number is occupied");
            }

        }

        //Send a message        private void button2_Click(object sender, EventArgs e)
        {
          
            if (socket != null)
            {
              
                // Parameter 1 The sent string is converted into a byte array                //Parameter 2 The remote terminal that sends data new IPEndPoint(("192.168.107.83"), 8081)                (Encoding.("Reverse Tiangang"), new IPEndPoint(("192.168.107.83"), 8081));
           }
        }

        //closure        private void button3_Click(object sender, EventArgs e)
        {
            ();//closure            socket = null;
        }

This is the end of this article about the implementation example of C# UDP network communication. For more related C# UDP network communication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!