CodeProject上有个例子是开个线程去同步接收,这样倒是可以满足我的程序需求,不过实际中遇到几个问题:
qq_client = new UdpClient();
IPEndPoint remoteQQEP = new IPEndPoint(remotehost, remoteport);
qq_client.Connect(remoteQQEP);
AsyncCallback GetRecvBuffer = new AsyncCallback(ReceiveCallback);
qq_client.BeginReceive(GetRecvBuffer, null);
这里用一个GetRecvBuffer的回掉来实现异步
{
try
{
lock (this)
{
byte[] recvbytes = qq_client.EndReceive(ar, ref remoteQQEP);
//QQFunction.DebugDump(recvbytes);
if (recvbytes[0] != QQDef.QQ_IM_HEAD && recvbytes[0] != 0x03)
{
//非QQ数据包
return;
}
switch (Pop16(recvbytes, 3))
{
case QQDef.QQ_REQUEST_TOKEN:
DoGetToken(recvbytes);
break;
case QQDef.QQ_REQUEST_LOGIN:
DoGetLogin(recvbytes);
break;
case QQDef.QQ_GET_ONLINE_FRIEND:
DoGetOnline(recvbytes);
break;
case QQDef.QQ_KEEP_ALIVE:
CheckAlive(recvbytes);
break;
case QQDef.QQ_SEND_IM_MSG:
// Do SomeThing
break;
case QQDef.QQ_RECV_IM_MSG:
DoRecvMsg(recvbytes);
break;
default:
QQFunction.DebugDump("UnKnow Command");
QQFunction.DebugDump(recvbytes);
break;
}
}
lock (this)
{
AsyncCallback GetRecvBuffer = new AsyncCallback(ReceiveCallback);
qq_client.BeginReceive(GetRecvBuffer, null);
}
}
catch
{
}
}