C#实现UDP协议

当只发送给一个终结点。

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UDPTest
{
    /// <summary>
    /// udp发送,只发送给一个节点
    /// </summary>
    class Program
    {
        static string _ip = "127.0.0.1";
        static int _port = 9001;
        static UdpClient _sendUdpClient = null;

        static void Main(string[] args)
        {
            _sendUdpClient = new UdpClient();//指定发送端口(0:任意可用端口)
            byte[] sendbytes = Encoding.Default.GetBytes("发送内容");
            
            IPAddress remoteIp = IPAddress.Parse(_ip);//接收消息的IP
            IPEndPoint remoteIpEndPoint = new IPEndPoint(remoteIp, _port);
            _sendUdpClient.Send(sendbytes, sendbytes.Length, remoteIpEndPoint);
            ReceiveMsg();

            Console.ReadLine();
        }

        /// <summary>
        /// 接收消息方法
        /// </summary>
        public static void ReceiveMsg()
        {            
            try
            {
                object callbackParam = null;
                _sendUdpClient.BeginReceive(new AsyncCallback(ReceiveCallback), callbackParam);//可能出现远程拒绝连接错误
            }
            catch (Exception ex)
            {             
                //处理ex

                if (_sendUdpClient != null)
                {
                    _sendUdpClient.Close();
                    _sendUdpClient = null;
                }
            }
        }

        /// <summary>
        /// 收到消息后的回调方法
        /// </summary>
        /// <param name="iar"></param>
        private static void ReceiveCallback(IAsyncResult iar)
        {
            try
            {
                IPEndPoint remoteIpEndPoint = null;
                byte[] receiveBytes = _sendUdpClient.EndReceive(iar, ref remoteIpEndPoint);
                //如果udp客户端发送消息给多个终结点,那可以根据接收消息函数返回的remoteIpEndPoint值来确定哪个ip返回来的消息。
                string message = Encoding.Default.GetString(receiveBytes);                
            }
            catch (Exception ex)
            {
               
            }
            finally
            {
               
            }
        }
    }
}
量变会引起质变。
原文地址:https://www.cnblogs.com/bibi-feiniaoyuan/p/udp.html