日期:2014-05-17 浏览次数:21095 次
public class StateObject
{
//服务器端
public Socket udpServer = null;
//接受数据缓冲区
public byte[] buffer = new byte[1024];
//远程终端
public EndPoint remoteEP;
}
public class AsynUdpServer
{
public StateObject state;
#region 服务器绑定终端节点
public void ServerBind()
{
//主机IP
IPEndPoint serverIp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8686);
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpServer.Bind(serverIp);
Console.WriteLine("server ready...");
IPEndPoint clientIp = new IPEndPoint(IPAddress.Any, 0);
state = new StateObject();
state.udpServer = udpServer;
state.remoteEP = (EndPoint)clientIp;
AsynRecive();
}
#endregion
#region 异步接受消息
public void AsynRecive()
{
state.udpServer.BeginReceiveFrom(state.buffer, 0, state.buffer.Length, SocketFlags.None, ref state.remoteEP,
new AsyncCallback(ReciveCallback), null);
}
#endregion
#region 异步接受消息回调函数
public void ReciveCallback(IAsyncResult asyncResult)
{
if (asyncResult.IsCompleted)
{
//获取发送端的终节点
IPEnd