110,538
社区成员
发帖
与我相关
我的任务
分享
class Program
{
// UDP连接
static UdpClient udpClient;
// 本机端口
static int localhostPort;
// 本机IP
static IPAddress localhostIPAddress;
// 本机节点
static IPEndPoint localhostIPEndPoint;
// 远程主机结点
static IPEndPoint tempEnd = new IPEndPoint(IPAddress.Any, 0);
// 判断是是否释放Udp连接
static bool isUdpNull = default(bool);
static void Main(string[] args)
{
// 初始化
Init();
// 异步接收
udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);
byte[] datagram = Encoding.UTF8.GetBytes("这是一个测试!!!");
//异步发送
udpClient.BeginSend(datagram, datagram.Length, localhostIPEndPoint, new AsyncCallback(SendCallback), udpClient);
// 停止异步接收
StopAsynchronousReceive();
Console.ReadKey();
}
// 初始化
static void Init()
{
localhostPort = 9000;
localhostIPAddress = IPAddress.Parse("127.0.0.1");
localhostIPEndPoint = new IPEndPoint(localhostIPAddress, localhostPort);
// 将UDP连接绑定终结点
udpClient = new UdpClient(localhostIPEndPoint);
}
// 停止异步接收
static void StopAsynchronousReceive()
{
byte[] datagram = new byte[] { 0xff };
udpClient.Send(datagram, datagram.Length, localhostIPEndPoint);
}
// 异步接收回调方法
static void ReceiveCallback(IAsyncResult ar)
{
object o = new object();
try
{
lock (o)
{
byte[] buffer = udpClient.EndReceive(ar, ref tempEnd);
if (tempEnd.Equals(localhostIPEndPoint) && buffer[0] == 0xff)
{
udpClient.Close();
isUdpNull = true;
}
else
{
Console.WriteLine("IP:{0} 消息内容:" + Encoding.UTF8.GetString(buffer), tempEnd.Address.ToString());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
lock (o)
{
if (!isUdpNull)
{
udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);
}
}
}
}
// 异步发送回调方法
static void SendCallback(IAsyncResult ar)
{
UdpClient tempUdpClient = (UdpClient)ar.AsyncState;
if (tempUdpClient != null)
{
Console.WriteLine("发送的字节数:{0}", tempUdpClient.EndSend(ar));
}
}
}
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
UdpClient.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);