using System; using System.Net.Sockets; using System.Net; //using HDL_ON.UI; namespace HDL_ON { /// /// 接收处理UDP数据包 /// /// public static class BusSocket { //监听端口 static int port; //本地Socket private static Socket busSocket; /// /// 启动Socket接收和发送功能 /// /// public static void Start (int port) { if (IsRunning) { return; } BusSocket.port = port; busSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); busSocket.EnableBroadcast = true; try { busSocket.Bind (new IPEndPoint (IPAddress.Any, port)); }catch{ busSocket = null; return; } //socket = new Socket (AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); //socket.Bind (new IPEndPoint (IPAddress.Parse (ip), 0)); //绑定套接字 //socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption (IPAddress.Parse ("224.0.168.188"))); //if (SetSocketOption () == false) error_occurred = true; asyncBeginReceive (); MainPage.Log ("BusSocket启动成功!"); } /// /// 停止Socket /// public static void Stop() { if (!IsRunning) { return; } try { busSocket.Close(); } catch { } busSocket = null; MainPage.Log("BusSocket关闭成功!"); } /// /// 当前的Socket是否运行 /// public static bool IsRunning { get { return null == busSocket ? false : true; } } /// /// 开始异步接收数据 /// private static void asyncBeginReceive() { if (!IsRunning) { 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); asyncBeginReceive (); } } /// /// 异步接收数据结束 /// /// private static void asyncEndReceive(IAsyncResult iar) { if (!IsRunning) { return; } try { asyncBeginReceive (); Packet packet = (Packet)iar.AsyncState; int len = busSocket.EndReceiveFrom(iar, ref packet.RemoteEndPoint); byte[] bytes = packet.Bytes; packet.Bytes = new byte[len]; System.Array.Copy(bytes, 0, packet.Bytes, 0, packet.Bytes.Length); packet.Manager(); } catch { } } /// /// 异步发送数据 /// /// public static 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}"); } } /// /// 异步发送数据结束 /// /// private static void asyncEndSend(IAsyncResult iar) { Packet tempUDPPacketBuffer = (Packet)iar.AsyncState; try { int bytesSent = busSocket.EndSendTo(iar); } catch { } } } }