C#下的Socket编程有同步和异步之,他们的具体区别偶还是没有完全搞清楚,最近研究的了一下这方便的东西,写在此做个记录。
在UDp监听某一端口通讯的时候,可以采用同步,使用线程,然后接受阻塞的模式,但是还可以使用异步的方法,比如下列子:
using System.Net.Sockets;
using System.Net;
using System;
using System.Text;
namespace Server
{
public class UdpServer
{
public class UdpState
{
public IPEndPoint e = null;
public UdpClient u = null;
}
public static UdpState s = new UdpState();
public static void ReceiveMessages()
{
IPEndPoint e = new IPEndPoint(IPAddress.Any, 10001);
UdpClient u = new UdpClient(e);
s.u = u;
u.BeginReceive(new AsyncCallback(ReceiveCallback), s);
}
/// <summary>
/// UDP异步回调函数
/// </summary>
/// <param name="ar"></param>
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
Byte[] receiveBytes = u.EndReceive(ar, ref s.e);
u.BeginReceive(new AsyncCallback(ReceiveCallback), ar.AsyncState);//重新开启异步接受
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
}
}
}
/// <summary>
/// 简单的发送客户端类
/// </summary>
public class UdpSendClient
{
public static UdpClient udpClient = new UdpClient();
public static void send()
{
udpClient.Connect("127.0.0.1", 10001);
Byte[] sendBytes = Encoding.ASCII.GetBytes("sendteststring");
udpClient.Send(sendBytes, sendBytes.Length);
}
}
想说的是这个异步接受就一定要得绑定端口,如果不绑定会报异常。