c# UDP protocol

UDP protocol

The Internet protocol suite supports a connectionless transport protocol called User Datagram Protocol (UDP). UDP provides a way for applications to send encapsulated IP packets without establishing a connection. RFC 768 describes UDP.
The Internet's transport layer has two main protocols that complement each other. Connectionless is UDP, which does little in particular except give applications the ability to send packets and allow them to architect their own protocols at the desired level. Connection-oriented is TCP, which does almost everything.

Advantages and Disadvantages of UDP

Advantages:
1. The communicating parties do not need to establish a connection before transmitting data, so there is no delay in connection establishment. On the sending end, the speed at which UDP transmits data is only limited by the speed at which the application generates data, the computer's capabilities, and the transmission bandwidth; at the receiving end, UDP puts each datagram in a queue, and the application reads each datagram from the queue. A datagram.
2. Transmitting data does not require maintaining connection status, including sending and receiving status, etc. In this way, a server can transmit the same data to multiple clients at the same time, such as implementing multicast.
Disadvantages:
Easy to lose packets
. It cannot provide reliability guarantee and data may be lost or damaged, so it is not suitable for transmitting important data. In addition, UDP cannot provide flow control, so it may cause network congestion.
Simple logic code:

 #region 单播
        /// <summary>
        /// 接收
        /// </summary>
        static void UdpRevice() 
        {
    
    
            Socket udp = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            IPEndPoint ipP = new IPEndPoint(IPAddress.Any,8080);

            udp.Bind(ipP);
            
            Task.Run(() =>
            {
    
    
                byte[] bytes = new byte[1024];
                while (true) 
                {
    
    
                    EndPoint endP = new IPEndPoint(0,0);
                    int length = udp.ReceiveFrom(bytes,ref endP);
                    if (length <= 0)
                    {
    
    
                        udp.Close();
                        return;
                    }
                    string str = encoding.GetString(bytes,0, length);
                    Console.WriteLine($"接收到{
      
      endP}发送过来的数据:"+ str);
                }
            });
        }
        static void UdpSend() 
        {
    
    
            Socket udp = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            Task.Run(() =>
            {
    
    
                //接收方IP和端口
                EndPoint endP = new IPEndPoint(IPAddress.Parse("192.168.22.1"),8080);
                //循环发送
                while (true)
                {
    
    
                    byte[] bytes = encoding.GetBytes("发送方发送的数据");
                    udp.SendTo(bytes, endP);
                    Task.Delay(1000).Wait();
                }
            });
        }
        #endregion
#region 组播

        /// <summary>
        /// 组播接收数据
        /// </summary>
        static void MulRevice() 
        {
    
    
            UdpClient udp = new UdpClient(8080);
            IPAddress ipAddress = IPAddress.Parse("235.0.0.1");
            //添加进组
            udp.JoinMulticastGroup(ipAddress);
            Task.Run(() => 
            {
    
    
                //发送方的IP和端口
                IPEndPoint endP = new IPEndPoint(0, 0);
                //循环接收数据
                while (true) 
                {
    
    
                    byte[] buffer = udp.Receive(ref endP);
                    string str = encoding.GetString(buffer);
                    Console.WriteLine($"组播:接收到的数据:{
      
      str}。发送方的IP和端口:{
      
      endP}");

                    //回消息,发送数据
                    byte[] bytes = encoding.GetBytes("接收消息后回消息");
                    udp.Send(bytes,bytes.Length,endP);
                }
            });
        }
        /// <summary>
        /// 组播发送数据
        /// </summary>
        static void MulSend() 
        {
    
    
            IPAddress ipAddress =IPAddress.Parse("235.0.0.1");
            UdpClient udpTo = new UdpClient(8088);//绑定本地的一个端口号
            udpTo.JoinMulticastGroup(ipAddress);
            Task.Run(() =>
            {
    
    
                //给组播发数据
                IPEndPoint endP = new IPEndPoint(ipAddress,8080);
                while (true) 
                {
    
    
                    byte[] bytes = encoding.GetBytes("给组播发的数据2222");
                    udpTo.Send(bytes,bytes.Length,endP);
                    byte[] bytes1 = udpTo.Receive(ref endP);
                    string str = encoding.GetString(bytes1);
                    Console.WriteLine($"发送之后,在接收一条接收方回应的消息:{
      
      str}。接收方的IP和端口是:========={
      
      endP}");
                    Task.Delay(1000).Wait();
                }
            });
        }
        #endregion
 #region 广播
        private static void BroadcastReceive() 
        {
    
    
            //自己的端口,别人发送数据时发送到这个端口
            UdpClient udpClient = new UdpClient(8080);
            Task.Run(() => 
            {
    
    
                IPEndPoint endP = new IPEndPoint(0,0);
                //循环接收数据
                while (true)
                {
    
    
                    //接收数据
                    byte[] buffer = udpClient.Receive(ref endP);
                    string str = encoding.GetString(buffer);
                    //输出
                    Console.WriteLine($"接收到的广播数据{
      
      str},发送数据的广播的IP和端口{
      
      endP}");
                }
            });
        }

        private static void BroadcastSend()
        {
    
    
            //发送时,不写端口,就会随机一个端口发送
            UdpClient udp = new UdpClient();
            Task.Run(() =>
            {
    
    
                //循环发送广播数据
                while (true)
                {
    
    
                    //广播IP:255.255.255.255
                    IPEndPoint endP = new IPEndPoint(IPAddress.Parse("255.255.255.255"),8080);
                    //循环发送
                    int num = 1;
                    while (true) 
                    {
    
    
                        byte[] bytes = encoding.GetBytes("我是广播"+num);
                        num++;
                        udp.Send(bytes,bytes.Length,endP);
                        Task.Delay(1000).Wait();
                    }
                }
            });
        }
        #endregion

Guess you like

Origin blog.csdn.net/qq_57212959/article/details/130761731
Recommended