C#实现
//定义结构体
public struct UdpState
{
public UdpClient u;
public IPEndPoint e;
}
private UdpClient _client; //_client的初始化请参考其他资料
IPEndPoint remoteEP = null; //TODO
//public static bool messageReceived = false;
EventWaitHandle _waitHandle = new AutoResetEvent(false);
//收到消息的回调方法
public void ReceiveCallback(IAsyncResult ar)
{
if (ar.AsyncState != null)
{
UdpState udpState = (UdpState)ar.AsyncState;
UdpClient u = udpState.u;
IPEndPoint e = udpState.e;
_recvBuffer = u.EndReceive(ar, ref e);
remoteEP = e;
//messageReceived = true;
_waitHandle.Set();
}
}
//消息处理
private void process()
{
UdpState s = new UdpState();
s.e = remoteEP;
s.u = _client;
while (true)
{
try
{
//_recvBuffer = _client.Receive(ref remoteEP); //同步阻塞方式接收消息
//以下是异步方式
//messageReceived = false;
_waitHandle.Reset();
_client.BeginReceive(new AsyncCallback(ReceiveCallback), s);
// Do some work while we wait for a message. For this example, we'll just sleep
//while (!messageReceived)
//{
// Thread.Sleep(100);
//}
_waitHandle.WaitOne();
//process _recvBuffer
IPEndPoint server = new IPEndPoint(remoteEP.Address, 6666); //具体端口视具体情况而定
byte[] data = null;
//data 赋值 回复
_client.Send(data, data.Length, server);
}
catch (Exception ex)
{
log.Debug("err:" + ex.Message,ex);
}
}
}