private void ReceiveSize(IAsyncResult ar)
{
this.nlock.AcquireWriterLock(Timeout.Infinite);
try
{
if (this.isDisconnected)
{
this.nlock.ReleaseWriterLock();
return;
}
if (buffer[0] == 0xFF && buffer[1] == 0xFF)
{
// if the buffer is marked as "empty", there was an error during reading
// normally happens if the client disconnects
// note: this is required as sock.Connected still can be true, even the client
// is already disconnected
this.nlock.ReleaseWriterLock();
ClientManager.EnterCriticalArea();
this.Disconnect();
ClientManager.LeaveCriticalArea();
return;
}
if (!sock.Connected)
{
this.nlock.ReleaseWriterLock();
ClientManager.EnterCriticalArea();
this.Disconnect();
ClientManager.LeaveCriticalArea();
return;
}
try { stream.EndRead(ar); }
catch (Exception)
{
this.nlock.ReleaseWriterLock();
ClientManager.EnterCriticalArea();
this.Disconnect();
ClientManager.LeaveCriticalArea();
return;
}
ushort size = BitConverter.ToUInt16(buffer, 0);
if (size < 4)
{
Logger.ShowWarning(sock.RemoteEndPoint.ToString() + " error: packet size is < 4",null);
/*try//this could crash the gateway somehow,so better ignore the Exception
{
ClientManager.EnterCriticalArea();
this.Disconnect();
ClientManager.LeaveCriticalArea();
}
catch (Exception ex)
{
Logger.ShowError(ex, null);
//sock.Disconnect(true);
sock.Close();
ClientManager.LeaveCriticalArea();
}*/
this.nlock.ReleaseWriterLock();
return;
}
if (sock.Available < (size - 2))
{
Logger.ShowWarning(sock.RemoteEndPoint.ToString() + string.Format(" error: packet data is too short, should be {0:G}", size - 2), null);
/*try//this could crash the gateway somehow,so better ignore the Exception
{
ClientManager.EnterCriticalArea();
this.Disconnect();
ClientManager.LeaveCriticalArea();
}
catch (Exception)
{
//sock.Disconnect(true);
sock.Close();
ClientManager.LeaveCriticalArea();
}*/
//this.nlock.ReleaseWriterLock();
//return;
}
byte[] data = new byte[size];
data[0] = buffer[0];
data[1] = buffer[1];
// mark buffer as "empty"
buffer[0] = 0xFF;
buffer[1] = 0xFF;
// Receive the data from the packet and call the receivedata function
// The packet is stored in AsyncState
//Console.WriteLine("New packet with size " + p.size);
try { this.nlock.ReleaseWriterLock(); stream.BeginRead(data, 2, size - 2, this.callbackData, data); }
catch (Exception)
{
//Logger.ShowError(ex, null);
ClientManager.EnterCriticalArea();
this.Disconnect();
ClientManager.LeaveCriticalArea();
return;
}
}
catch (Exception e) { Logger.ShowError(e, null); }
}