UDP及其组播,接收发送封装

1.Receiver

 public class Receiver
{
public delegate void HeartBeat(byte[] data);
public event HeartBeat Heart; #region 内部变量
private int size = ;
private UdpClient newsock;
private Thread t;
private int m_port;
private IPEndPoint sender;
#endregion /// <summary>
/// UDP开始接收指定端口数据
/// </summary>
/// <param name="port"></param>
public void Start(string port)
{
Int32.TryParse(port, out m_port); newsock = new UdpClient(m_port);
newsock.EnableBroadcast = true;
newsock.MulticastLoopback = true; sender = new IPEndPoint(IPAddress.Any, m_port);
t = new Thread(start);
t.IsBackground = true;
t.Start();
} public void Dispose()
{
if (newsock != null)
{
newsock.Close();
} if (t != null && t.ThreadState == ThreadState.Running)
{ t.Abort(); } } void start()
{
try
{
byte[] data; while (true)
{
if (newsock == null)
{
return;
}
if (newsock.Available <= )
{
continue;
}
if (newsock.Client == null)
{
return;
} data = newsock.Receive(ref sender); if (Heart != null)
{
Heart(data);
}
} }
catch (Exception e)
{ } } public void Join(string ip,string port)
{
Int32.TryParse(port, out m_port); newsock = new UdpClient(m_port);
newsock.EnableBroadcast = true;
newsock.MulticastLoopback = true; sender = new IPEndPoint(IPAddress.Any, m_port); if (newsock != null)
{
newsock.JoinMulticastGroup(IPAddress.Parse(ip));
} t = new Thread(start);
t.IsBackground = true;
t.Start();
} public void Leave(string ip)
{
if (newsock != null)
newsock.DropMulticastGroup(IPAddress.Parse(ip));
} }

2.UdpSender

  public class UdpSender
{
private UdpClient sendsock;
private int m_sendport;
private IPEndPoint m_SendPoint;
private static object _LockObj = new object(); /// <summary>
/// 单点UDP初始化
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
public void SetSend(string ip, string port)
{
Int32.TryParse(port, out m_sendport);
m_SendPoint = new IPEndPoint(IPAddress.Parse(ip), m_sendport); sendsock = new UdpClient
{
EnableBroadcast = true,
MulticastLoopback = true
};
} public void SendMsg(byte[] data)
{
lock (_LockObj)
{
if (sendsock != null)
{
sendsock.Send(data, data.Length, m_SendPoint);
}
} } public void Dispose()
{
if (sendsock != null)
{
sendsock.Close();
}
} /// <summary>
/// UDP组播初始化
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
public void Join(string ip, string port)
{
Int32.TryParse(port, out m_sendport);
sendsock = new UdpClient
{
EnableBroadcast = true,
MulticastLoopback = true
};
m_SendPoint = new IPEndPoint(IPAddress.Parse(ip), m_sendport);
sendsock.JoinMulticastGroup(IPAddress.Parse(ip));
} public void Leave(string ip)
{
if (sendsock != null)
sendsock.JoinMulticastGroup(IPAddress.Parse(ip));
} }
上一篇:微信扫码下载apk


下一篇:用SVN check out项目后第三方库丢失