日期:2014-05-17 浏览次数:21074 次
private static ManualResetEvent AllDone = new ManualResetEvent(false);
private static void AcceptCallback(IAsyncResult ar)
{
try
{
AllDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
Entity entity = new Entity()
{
SocketInstance = handler
};
// ...
handler.BeginReceive(entity.TempBuffer, 0, 1024, 0, new AsyncCallback(ReadCallback), entity);
}
catch (Exception ex)
{
WriteErrorLog(ex);
}
}
private static void ReadCallback(IAsyncResult ar)
{
try
{
Entity entity = (Entity)ar.AsyncState;
Socket handler = entity.SocketInstance;
int bytReceiveLen = handler.EndReceive(ar);
if (bytReceiveLen > 0)
{
entity.LastCommunicaTime = DateTime.Now;
GeneralHelper.ByteHelper.BytArrAppend(ref entity.FullBuffer, entity.TempBuffer, bytReceiveLen);
if (bytReceiveLen < 1024)
{
// ...
}
handler.BeginReceive(entity.TempBuffer, 0, 1024, 0, new AsyncCallback(ReadCallback), entity);
}
else
{
RemoveEntity(handler);
}
}
catch (SocketException se)
{
WriteErrorLog(ex);
}
catch (Exception ex)
{
WriteErrorLog(ex);
}
}