[fix]修正UdpServer在接收广播时连续启动接收的错误,在StarAgent中,此时可能收到广播包,SocketFlags是Broadcast,需要清空,否则报错“参考的对象类型不支持尝试的操作”; 无需设置SocketOptionName.PacketInformation,在ReceiveMessageFromAsync时会自动设置,并且支持ipv6;
石头 authored at 2024-10-10 00:36:00 石头 committed at 2024-10-10 00:45:43
1.83 KiB
X
using System.Collections.Generic;
using System.Net;


namespace System
{
    /// <summary>网络结点扩展</summary>
    public static class EndPointExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public static String ToAddress(this EndPoint endpoint)
        {
            return ((IPEndPoint)endpoint).ToAddress();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public static String ToAddress(this IPEndPoint endpoint)
        {
            return String.Format("{0}:{1}", endpoint.Address, endpoint.Port);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static IPEndPoint ToEndPoint(this String address)
        {
            var array = address.Split(new String[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
            if (array.Length != 2)
            {
                throw new Exception("Invalid endpoint address: " + address);
            }
            var ip = IPAddress.Parse(array[0]);
            var port = Int32.Parse(array[1]);
            return new IPEndPoint(ip, port);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="addresses"></param>
        /// <returns></returns>
        public static IEnumerable<IPEndPoint> ToEndPoints(this String addresses)
        {
            var array = addresses.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            var list = new List<IPEndPoint>();
            foreach (var item in array)
            {
                list.Add(item.ToEndPoint());
            }
            return list;
        }
    }
}