using System;
using System.Net.Sockets;
using System.Net;
using Newtonsoft.Json.Linq;
namespace HDL_ON
{
public class UdpSocket
{
static UdpSocket _busSocket;
public static UdpSocket _BusSocket
{
get
{
if(_busSocket == null)
{
_busSocket = new UdpSocket();
}
return _busSocket;
}
}
///
/// 监听端口
///
public int port
{
get
{
if (MainPage.LoginUser != null && Entity.DB_ResidenceData.residenceData != null)
{
return Entity.DB_ResidenceData.residenceData.GatewayType == 0 ? 6000 : 8585;
}
return 6000;
}
}
//本地Socket
private Socket busSocket;
///
/// 启动Socket接收和发送功能
///
public void Start ()
{
if (IsRunning || 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")));
}
catch{
busSocket = null;
return;
}
asyncBeginReceive();
MainPage.Log ($"udp port : {port}");
}
///
/// 停止Socket
///
public void Stop()
{
if (!IsRunning)
{
return;
}
try
{
busSocket.Close();
}
catch { }
busSocket = null;
MainPage.Log("Socket关闭");
}
///
/// 当前的Socket是否运行
///
public bool IsRunning
{
get
{
return null == busSocket ? false : true;
}
}
///
/// 开始异步接收数据
///
private 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 ();
Console.WriteLine($"asyncBeginReceive {e.Message}");
}
}
///
/// 搜索网络设备触发的回调事件
///
public Action SearchNetDeviceAction;
///
/// 异步接收数据结束
///
///
private 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];
Array.Copy(bytes, 0, packet.Bytes, 0, packet.Bytes.Length);
//mqtt连接数据读取 A协议网络设备信息读取回复 处理
if (((IPEndPoint)packet.RemoteEndPoint).Port == 8585)
{
var reString = System.Text.Encoding.UTF8.GetString(bytes);
var jt = Newtonsoft.Json.JsonConvert.DeserializeObject(reString);
JToken jtc = null;
jt.TryGetValue("command", out jtc);
if (jtc != null && jtc.ToString() == "search_response")
{
JToken jto = null;
jt.TryGetValue("objects", out jto);
if (jto != null)
{
SearchNetDeviceAction?.Invoke(jto.ToString());
}
}
}
else if(((IPEndPoint)packet.RemoteEndPoint).Port == 6000)//处理bus 6000端口的数据
{
packet.Manager();
}
}
catch (Exception ex)
{
MainPage.Log($"异步接收数据结束 {ex.Message},{((Packet)iar.AsyncState).Bytes}");
}
}
///
/// 异步发送数据
///
///
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}");
}
}
///
/// 异步发送数据结束
///
///
private void asyncEndSend(IAsyncResult iar)
{
Packet tempUDPPacketBuffer = (Packet)iar.AsyncState;
try
{
int bytesSent = busSocket.EndSendTo(iar);
}
catch {
}
}
}
}