Efficient.Net UDP asynchronous programming implementation analysis

  • 2020-05-19 04:31:43
  • OfStack

Because want to write a web application will use UDP agreement, UDP the things more troublesome, and provide reliable connection, unlike TCP1 sample to send and receive timeout design, it is no good to the last as long as the packet - use Timer to detect if want _ #, but this is not the key, the key is how to establish an efficient UDP mechanism to receive real-time server sends packets.

An example on CodeProject is to open a thread to receive synchronously, which can satisfy my program requirements. However, I encountered several problems in practice:
1. The program costs a lot, the memory is crazy, connect the data once to open the thread again once
2. Because the main interface and the bottom layer are completely separated and only communicate through the middle interface, the thread always fails to end normally, and there is still a process that does not know what to do after the program ends.
Therefore, I thumbing through MSDN, looking for the code I wrote before, and finally decided to use asynchrony to receive. The example of UDP asynchrony on MSDN is not very good, which is a little perfunctory. Using asynchrony is a good solution to the above problems and efficient completion, the code is as follows:
 
UdpClient qq_client; //Udp The client  
qq_client = new UdpClient(); 
IPEndPoint remoteQQEP = new IPEndPoint(remotehost, remoteport); 
qq_client.Connect(remoteQQEP); 
AsyncCallback GetRecvBuffer = new AsyncCallback(ReceiveCallback); 
qq_client.BeginReceive(GetRecvBuffer, null); 
 Here with 1 a GetRecvBuffer To implement asynchrony  
private void ReceiveCallback(IAsyncResult ar) 
{ 
try 
{ 
lock (this) 
{ 
byte[] recvbytes = qq_client.EndReceive(ar, ref remoteQQEP); 
//QQFunction.DebugDump(recvbytes); 
if (recvbytes[0] != QQDef.QQ_IM_HEAD && recvbytes[0] != 0x03) 
{ 
// non QQ The packet  
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 
{ 
} 
} 

Is the code simple? Is it powerful?

Related articles: