C# UDP Programming (Local Area Network Communication via UdpClient-like)

1. UDP (User Data Protocol)
(1) UDP is a non-connected protocol. Before transferring data, the source and terminal do not establish a connection. When it wants to transfer data, it simply grabs the data from the application program and throws it on the network as quickly as possible. At the sender, the speed of UDP transmitting data is limited only by the speed of data generated by the application, the ability of the computer and the transmission bandwidth; at the receiver, UDP places each message segment in a queue, and the application reads one message segment from the queue at a time.
(2) Because the transmission data does not establish a connection, there is no need to maintain the connection status, including receiving and receiving status, so a server can transmit the same message to multiple clients at the same time.
(3) The title of UDP packet is very short, only 8 bytes, and the extra cost is very small compared with 20 bytes of TCP packet.
(4) Throughput is not regulated by congestion control algorithm, but is limited by the rate of data generated by application software, transmission bandwidth, source and terminal host performance.
(5) UDP uses the best effort to deliver, that is, it does not guarantee reliable delivery, so the host does not need to maintain a complex linked state table (there are many parameters).
(6) UDP is message-oriented. The UDP of the sender delivers the message handed down by the application to the IP layer after adding the header. Instead of splitting or merging, the boundaries of these messages are preserved, so the application needs to choose the appropriate size of the message.
We often use "ping" command to test whether the TCP/IP communication between two hosts is normal. In fact, the principle of "ping" command is to send UDP data packets to the other host, and then the other host confirms receipt of the data packets. If the message of whether the data packets arrived back in time, then the network is all right.
a. What is the maximum size of each udp package?
65507 is about 64K

b. Why is the maximum 65507?
Because udp headers have two bytes for recording the length of inclusions. Two bytes represent the maximum value: 2^16-1=64K-1=65535
udp header 8 bytes, ip header 20 bytes, 65535-28 = 65507

c. What if the udp message to be sent is greater than 65507?
The application layer needs to be sent by the developers themselves in fragments. The granularity of the fragments is up to 65507 bytes. The sendto function of the system does not support single packet sending with more than 65507 bytes.
2. A Simple Communication Program Implemented by C#UDPClient Class

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace UDPClient_Server
{
    public partial class UDPForm : Form
    {

        UdpClient udpClient;
        IPEndPoint locatePoint;

        public UDPForm()
        {
            InitializeComponent();
        }

        private void UDPForm_Load(object sender, EventArgs e)
        {
            txtLocateIP.Text = getIPAddress();
            txtRemoteIP.Text = getIPAddress();
            //Prohibit hyperbole thread monitoring
            Control.CheckForIllegalCrossThreadCalls = false;//This method is not good, but convenient and not advocated.
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnServer_Click(object sender, EventArgs e)
        {
           // btnClient.Enabled = false;
            if (udpClient != null)
                return;

            IPAddress locateIp = IPAddress.Parse(txtLocateIP.Text);
            locatePoint = new IPEndPoint(locateIp, Convert.ToInt32(txtLocatePort.Text));
            udpClient = new UdpClient(locatePoint);

            //Once the listener is created, it begins to receive information and create a thread
            Thread th = new Thread(Receive);
            th.IsBackground = true;
            th.Start();
        }

        /// <summary>
        /// Receiving Thread Method
        /// </summary>
        void Receive()
        {

            byte[] recBuffer;
            //Remote IP
            IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try
                {

                    recBuffer = udpClient.Receive(ref remotePoint);
                    if (recBuffer != null)
                    {
                        string str = System.Text.Encoding.UTF8.GetString(recBuffer,0,recBuffer.Length);
                        rtxtRec.AppendText(remotePoint.ToString()+str+"\r\n");
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
        }


        private void btnSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(rtxtSend.Text.Trim()))
                return;

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(rtxtSend.Text.Trim());
            IPAddress remoteIp = IPAddress.Parse(txtLocateIP.Text);
            IPEndPoint remotePoint = new IPEndPoint(remoteIp, Convert.ToInt32(txtRemotePort.Text));
            udpClient.Send(buffer, buffer.Length, remotePoint);

        }

        /// <summary>
        /// Get local IP Method
        /// </summary>
        /// <returns></returns>
        private string getIPAddress()
        {

            //Get all local IP addresses
            IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] ip = ipe.AddressList;
            for (int i = 0; i < ip.Length; i++)
            {
                if (ip[i].AddressFamily.ToString().Equals("InterNetwork"))
                {

                    return ip[i].ToString();
                }
            }
            return null;
        }
    }
}

Keywords: network encoding DNS Windows

Added by lachild on Thu, 11 Jul 2019 03:34:26 +0300