using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ToolsClassLibrary
{
///
/// UDP传输类
///
public class UdpHelper
{
#region 容器对象
///
/// 容器对象
///
public class StateObject
{
//服务器端
public Socket udpServer = null;
//接受数据缓冲区
public byte[] buffer = new byte[1024];
//远程终端
public EndPoint remoteEP;
}
public StateObject state;
public void Close()
{
state.udpServer.Close();
state.udpServer.Dispose();
}
#endregion
#region 服务器广播发送端
public void ServerBind(string ipAddress, int port)
{
try
{
state = new StateObject();
state.udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
state.udpServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
if (ipAddress == "0.0.0.0")
{
state.remoteEP = new IPEndPoint(IPAddress.Broadcast, port);
}
else
{
state.remoteEP = new IPEndPoint(IPAddress.Parse(ipAddress), port);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
public void SendTo(byte[] dataString)
{
try
{
state.udpServer.SendTo(dataString, state.remoteEP);
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
#endregion
#region 客户接收端
public void ClientBind()
{
IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
string ip = "";
for (int i = 0; i != IpEntry.AddressList.Length; i++)
{
if (!IpEntry.AddressList[i].IsIPv6LinkLocal
&& !IpEntry.AddressList[i].IsIPv6Multicast
&& !IpEntry.AddressList[i].IsIPv6SiteLocal
&& !IpEntry.AddressList[i].IsIPv6Teredo)
{
ip = IpEntry.AddressList[i].ToString();
}
}
Console.WriteLine("客户端Udp模式");
state = new StateObject();
state.udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
state.udpServer.Bind(new IPEndPoint(IPAddress.Parse(ip), 8787));
state.remoteEP = new IPEndPoint(IPAddress.Any, 0);
}
public byte[] Receive()
{
state.buffer = new byte[1024*1024];
try
{
int length = state.udpServer.ReceiveFrom(state.buffer, ref state.remoteEP);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
}
return state.buffer;
}
#endregion
}
}