wxr
2024-01-03 413e7024c298d7c04d425c8a1970613b2b37b619
HDL_ON/DAL/DriverLayer/UdpSocket.cs
@@ -1,447 +1,222 @@
//using System;
//using System.Net.Sockets;
//using System.Net;
//namespace HDL_ON.DriverLayer
//{
//   public class UdpSocket
//   {
//      static UdpSocket _busSocket;
//      public static UdpSocket _BusSocket
//        {
//            get
//            {
//            if(_busSocket == null)
//                {
//               _busSocket = new UdpSocket();
//                }
//            return _busSocket;
//            }
//        }
//      //本地Socket
//      private Socket busSocket;
//      public int Port = 0;
//      /// <summary>
//      /// 启动Socket接收和发送功能
//      /// </summary>
//      public void Start (int port = 0)
//        {
//         if (IsRunning)
//         {
//            if (port == Port)
//                {
//                    return;
//            }
//                else
//                {
//                    busSocket.Close();
//            }
//            }
//         if (port != 0)
//            Port = port;
//         if (Port == 0)
//            return;
//            busSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//            busSocket.EnableBroadcast = true;
//            try {
//            busSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
//            busSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.0.168.188")));
//            relinkCount = 0;
//         }
//         catch (Exception ex){
//            MainPage.Log ($"udp port bind error : {ex.Message}");
//            busSocket = null;
//                return;
//            }
//            asyncBeginReceive();
//            MainPage.Log ($"udp port : {port}");
//        }
//      /// <summary>
//      /// 停止Socket
//      /// </summary>
//      public void Stop()
//      {
//         if(busSocket == null)
//            {
//            return;
//            }
//         if (!IsRunning)
//         {
//            return;
//         }
//         try
//         {
//            busSocket.Close();
//            relinkCount = 0;
//         }
//         catch { }
//         busSocket = null;
//         MainPage.Log("Socket关闭");
//      }
//      /// <summary>
//      /// 当前的Socket是否运行
//      /// </summary>
//      public bool IsRunning
//      {
//         get
//         {
//            return null == busSocket ? false : true;
//         }
//      }
//      /// <summary>
//      /// 开始异步接收数据
//      /// </summary>
//      private void asyncBeginReceive()
//      {
//         if (!IsRunning)
//         {
//            return;
//         }
//         if(busSocket == null)
//            {
//            return;
//            }
//            try {
//                Packet packet = new Packet ();
//                busSocket.BeginReceiveFrom (packet.Bytes, 0, packet.Bytes.Length, SocketFlags.None, ref packet.RemoteEndPoint, new AsyncCallback (asyncEndReceive), packet);
//            }
//            catch (Exception e) {
//                System.Threading.Thread.Sleep (1);
//                Console.WriteLine("asyncBeginReceive " + relinkCount   );
//            if (relinkCount == 0)
//            {
//               relinkCount = 1;
//               asyncBeginReceive();
//            }
//                Console.WriteLine($"asyncBeginReceive {e.Message}");
//            }
//      }
//      /// <summary>
//        /// 重连次数
//        /// </summary>
//      private int relinkCount = 0;
//      /// <summary>
//      /// 异步接收数据结束
//      /// </summary>
//      /// <param name="iar"></param>
//      private void asyncEndReceive(IAsyncResult iar)
//      {
//         if (!IsRunning)
//         {
//            return;
//         }
//         try
//         {
//            if (busSocket == null)
//            {
//               return;
//            }
//            asyncBeginReceive();
//            Packet packet = (Packet)iar.AsyncState;
//            int len = busSocket.EndReceiveFrom(iar, ref packet.RemoteEndPoint);
//            byte[] bytes = packet.Bytes;
//            packet.Bytes = new byte[len];
//            Array.Copy(bytes, 0, packet.Bytes, 0, packet.Bytes.Length);
//            //MainPage.Log($"接收{packet.RemoteEndPoint}数据");
//            //mqtt连接数据读取  A协议网络设备信息读取回复 处理
//            if (((IPEndPoint)packet.RemoteEndPoint).Port == 8585)
//            {
//               Control.Ins.ConvertReceiveData(bytes, ((IPEndPoint)packet.RemoteEndPoint).Address.ToString());
//            }
//            else if (((IPEndPoint)packet.RemoteEndPoint).Port == 6000)//处理bus 6000端口的数据
//            {
//               packet.Manager();
//            }
//         }
//         catch (Exception ex)
//         {
//            MainPage.Log($"异步接收数据结束 {ex.Message},{((Packet)iar.AsyncState).Bytes}");
//         }
//      }
//      /// <summary>
//      /// 异步发送数据
//      /// </summary>
//      /// <param name="tempPacket"></param>
//      public void AsyncBeginSend(Packet tempPacket)
//      {
//         try
//         {
//            if (!IsRunning)
//            {
//               tempPacket.HaveSendCount++;
//               return;
//            }
//            tempPacket.FlagDateTime = System.DateTime.Now;
//            tempPacket.HaveSendCount++;
//            busSocket.BeginSendTo(tempPacket.Bytes, 0, tempPacket.Bytes.Length, SocketFlags.None, tempPacket.RemoteEndPoint, new AsyncCallback(asyncEndSend), tempPacket);
//         }
//         catch (Exception ex)
//         {
//            MainPage.Log($"AsyncBeginSend error {ex.Message}");
//         }
//      }
//      /// <summary>
//      /// 异步发送数据结束
//      /// </summary>
//      /// <param name="iar"></param>
//      private void asyncEndSend(IAsyncResult iar)
//      {
//         Packet tempUDPPacketBuffer = (Packet)iar.AsyncState;
//         try
//         {
//            int bytesSent = busSocket.EndSendTo(iar);
//         }
//         catch {
//            }
//      }
//   }
//}
using System;
using System;
using System.Net.Sockets;
using System.Net;
namespace HDL_ON.DriverLayer
{
   public class UdpSocket
   {
      static UdpSocket _busSocket;
      public static UdpSocket _BusSocket
      {
         get
         {
            if (_busSocket == null)
            {
               _busSocket = new UdpSocket();
            }
            return _busSocket;
         }
      }
    public class UdpSocket
    {
        static UdpSocket _busSocket;
        public static UdpSocket _BusSocket
        {
            get
            {
                if (_busSocket == null)
                {
                    _busSocket = new UdpSocket();
                }
                return _busSocket;
            }
        }
      //本地Socket
      private Socket busSocket;
      public int Port = 0;
      /// <summary>
      /// 启动Socket接收和发送功能
      /// </summary>
      public void Start(int port = 0)
      {
         if (IsRunning)
         {
            if (port == Port)
            {
               return;
            }
            else
            {
               busSocket.Close();
            }
         }
         if (port != 0)
            Port = port;
         if (Port == 0)
            return;
        //本地Socket
        private Socket busSocket;
        public int Port = 0;
        /// <summary>
        /// 启动Socket接收和发送功能
        /// </summary>
        public void Start(int port = 0)
        {
            if (IsRunning)
            {
                if (port == Port)
                {
                    return;
                }
                else
                {
                    busSocket.Close();
                }
            }
            if (port != 0)
                Port = port;
            if (Port == 0)
                return;
         busSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         busSocket.EnableBroadcast = true;
         try
         {
            busSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
            busSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            busSocket.EnableBroadcast = true;
            try
            {
                busSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
            busSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.0.168.188")));
            relinkCount = 0;
         }
         catch (Exception ex)
         {
            MainPage.Log($"udp port bind error : {ex.Message}");
                busSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.0.168.188")));
                relinkCount = 0;
            }
            catch (Exception ex)
            {
                MainPage.Log($"udp port bind error : {ex.Message}");
            busSocket = null;
            return;
         }
                busSocket = null;
                return;
            }
         asyncBeginReceive();
            asyncBeginReceive();
         MainPage.Log($"udp port : {port}");
      }
            MainPage.Log($"udp port : {port}");
        }
      /// <summary>
      /// 停止Socket
      /// </summary>
      public void Stop()
      {
         if (busSocket == null)
         {
            return;
         }
         if (!IsRunning)
         {
            return;
         }
         try
         {
            busSocket.Close();
            relinkCount = 0;
         }
         catch { }
         busSocket = null;
         MainPage.Log("Socket关闭");
      }
        /// <summary>
        /// 停止Socket
        /// </summary>
        public void Stop()
        {
            if (busSocket == null)
            {
                return;
            }
            if (!IsRunning)
            {
                return;
            }
            try
            {
                busSocket.Close();
                relinkCount = 0;
            }
            catch { }
            busSocket = null;
            MainPage.Log("Socket关闭");
        }
      /// <summary>
      /// 当前的Socket是否运行
      /// </summary>
      public bool IsRunning
      {
         get
         {
            return null == busSocket ? false : true;
         }
      }
        /// <summary>
        /// 当前的Socket是否运行
        /// </summary>
        public bool IsRunning
        {
            get
            {
                return null == busSocket ? false : true;
            }
        }
      byte []receiveBytes = new byte[2000];
        /// <summary>
        /// 开始异步接收数据
        /// </summary>
        private void asyncBeginReceive()
        {
            if (!IsRunning)
            {
                return;
            }
            if (busSocket == null)
            {
                return;
            }
      /// <summary>
      /// 开始异步接收数据
      /// </summary>
      private void asyncBeginReceive()
      {
         if (!IsRunning)
         {
            return;
         }
         if (busSocket == null)
         {
            return;
         }
         try
         {
            int len = busSocket.Receive(receiveBytes, SocketFlags.None);
            Packet packet = new Packet(len);
            System.Array.Copy(receiveBytes, packet.Bytes, len);
                packet.Manager();
         }
         catch (Exception e)
         {
            System.Threading.Thread.Sleep(1);
            Console.WriteLine("asyncBeginReceive " + relinkCount);
            if (relinkCount == 0)
            {
               relinkCount = 1;
               asyncBeginReceive();
            }
            Console.WriteLine($"asyncBeginReceive {e.Message}");
         }
      }
      /// <summary>
      /// 重连次数
      /// </summary>
      private int relinkCount = 0;
            try
            {
                Packet packet = new Packet();
                busSocket.BeginReceiveFrom(packet.Bytes, 0, packet.Bytes.Length, SocketFlags.None, ref packet.RemoteEndPoint, new AsyncCallback(asyncEndReceive), packet);
            }
            catch (Exception e)
            {
                System.Threading.Thread.Sleep(1);
                Console.WriteLine("asyncBeginReceive " + relinkCount);
                if (relinkCount == 0)
                {
                    relinkCount = 1;
                    asyncBeginReceive();
                }
                Console.WriteLine($"asyncBeginReceive {e.Message}");
            }
        }
        /// <summary>
        /// 重连次数
        /// </summary>
        private int relinkCount = 0;
      /// <summary>
      /// 异步接收数据结束
      /// </summary>
      /// <param name="iar"></param>
      private void asyncEndReceive(IAsyncResult iar)
      {
         if (!IsRunning)
         {
            return;
         }
         try
         {
            if (busSocket == null)
            {
               return;
            }
            asyncBeginReceive();
            Packet packet = (Packet)iar.AsyncState;
            int len = busSocket.EndReceiveFrom(iar, ref packet.RemoteEndPoint);
        /// <summary>
        /// 异步接收数据结束
        /// </summary>
        /// <param name="iar"></param>
        private void asyncEndReceive(IAsyncResult iar)
        {
            if (!IsRunning)
            {
                return;
            }
            try
            {
                if (busSocket == null)
                {
                    return;
                }
                asyncBeginReceive();
                Packet packet = (Packet)iar.AsyncState;
                int len = busSocket.EndReceiveFrom(iar, ref packet.RemoteEndPoint);
            byte[] bytes = packet.Bytes;
            packet.Bytes = new byte[len];
            Array.Copy(bytes, 0, packet.Bytes, 0, packet.Bytes.Length);
                byte[] bytes = packet.Bytes;
                packet.Bytes = new byte[len];
                Array.Copy(bytes, 0, packet.Bytes, 0, packet.Bytes.Length);
            //MainPage.Log($"接收{packet.RemoteEndPoint}数据");
            //mqtt连接数据读取  A协议网络设备信息读取回复 处理
            if (((IPEndPoint)packet.RemoteEndPoint).Port == 8585)
            {
               Control.Ins.ConvertReceiveData(bytes, ((IPEndPoint)packet.RemoteEndPoint).Address.ToString());
            }
            else if (((IPEndPoint)packet.RemoteEndPoint).Port == 6000)//处理bus 6000端口的数据
            {
               packet.Manager();
            }
                //MainPage.Log($"接收{packet.RemoteEndPoint}数据");
                //mqtt连接数据读取  A协议网络设备信息读取回复 处理
                if (((IPEndPoint)packet.RemoteEndPoint).Port == 8585)
                {
                    Control.Ins.ConvertReceiveData(bytes, ((IPEndPoint)packet.RemoteEndPoint).Address.ToString());
                }
                else if (((IPEndPoint)packet.RemoteEndPoint).Port == 6000)//处理bus 6000端口的数据
                {
                    packet.Manager();
                }
         }
         catch (Exception ex)
         {
            MainPage.Log($"异步接收数据结束 {ex.Message},{((Packet)iar.AsyncState).Bytes}");
         }
      }
            }
            catch (Exception ex)
            {
                MainPage.Log($"异步接收数据结束 {ex.Message},{((Packet)iar.AsyncState).Bytes}");
            }
        }
      /// <summary>
      /// 异步发送数据
      /// </summary>
      /// <param name="tempPacket"></param>
      public void AsyncBeginSend(Packet tempPacket)
      {
         try
         {
            if (!IsRunning)
            {
               tempPacket.HaveSendCount++;
               return;
            }
            tempPacket.FlagDateTime = System.DateTime.Now;
            tempPacket.HaveSendCount++;
            busSocket.BeginSendTo(tempPacket.Bytes, 0, tempPacket.Bytes.Length, SocketFlags.None, tempPacket.RemoteEndPoint, new AsyncCallback(asyncEndSend), tempPacket);
         }
         catch (Exception ex)
         {
            MainPage.Log($"AsyncBeginSend error {ex.Message}");
         }
      }
        /// <summary>
        /// 异步发送数据
        /// </summary>
        /// <param name="tempPacket"></param>
        public void AsyncBeginSend(Packet tempPacket)
        {
            try
            {
                if (!IsRunning)
                {
                    tempPacket.HaveSendCount++;
                    return;
                }
                tempPacket.FlagDateTime = System.DateTime.Now;
                tempPacket.HaveSendCount++;
                busSocket.BeginSendTo(tempPacket.Bytes, 0, tempPacket.Bytes.Length, SocketFlags.None, tempPacket.RemoteEndPoint, new AsyncCallback(asyncEndSend), tempPacket);
            }
            catch (Exception ex)
            {
                MainPage.Log($"AsyncBeginSend error {ex.Message}");
            }
        }
      /// <summary>
      /// 异步发送数据结束
      /// </summary>
      /// <param name="iar"></param>
      private void asyncEndSend(IAsyncResult iar)
      {
         Packet tempUDPPacketBuffer = (Packet)iar.AsyncState;
         try
         {
            int bytesSent = busSocket.EndSendTo(iar);
         }
         catch
         {
        /// <summary>
        /// 异步发送数据结束
        /// </summary>
        /// <param name="iar"></param>
        private void asyncEndSend(IAsyncResult iar)
        {
            Packet tempUDPPacketBuffer = (Packet)iar.AsyncState;
            try
            {
                int bytesSent = busSocket.EndSendTo(iar);
            }
            catch
            {
         }
      }
   }
}
            }
        }
    }
}