void BytesToQueueProcessor()
{
try
{
ServerStream = Client.GetStream();
if (this.Connected != null)
{
Connected(this, new ConnectionEventArgs(this.ID));
}
byte[] buff = null;
//List<byte> buffer = null;
int bytesRead = 0;
int currentBlock = 0;
do
{
using (MemoryStream msBuffer = new MemoryStream())
{
byte[] wrkBuff = null;
do
{
buff = new byte[8];
currentBlock = 0;
//buffer = new List<byte>();
#region Get Packet Length
bytesRead = ServerStream.Read(buff, 0, buff.Length);
if (bytesRead > 0)
{
byte[] wrkByte = new byte[bytesRead];
Array.Copy(buff, 0, wrkByte, 0, bytesRead);
currentBlock += bytesRead;
//buffer.AddRange(buff);
msBuffer.Write(buff, 0, bytesRead);
//Code here to fix error with packet and try to self-adjust. This may cause packets to be ignored.
//if (buffer.Count >= 4)
if (msBuffer.Length >= 4)
{
wrkBuff = msBuffer.GetBuffer();
int pos = 0;
int headerID = 0;
do
{
//headerID = BitConverter.ToInt32(buffer.ToArray(), 0);
headerID = BitConverter.ToInt32(wrkBuff, pos);
if (headerID != StandardID)
{
pos++;
//buffer.RemoveAt(0);
}
} while (pos < wrkBuff.Length - 3 && headerID != StandardID);
}
}
} while (msBuffer != null && msBuffer.Length < 8 && bytesRead > 0);
#endregion
if (bytesRead > 0 && msBuffer != null && msBuffer.Length >= 8)
{
int ln = BitConverter.ToInt32(wrkBuff, 4);
buff = new byte[ln];
int remainToRead = ln - 8;
if (remainToRead > 0)
{
do
{
bytesRead = ServerStream.Read(buff, 0, remainToRead);
if (bytesRead > 0)
{
currentBlock += bytesRead;
//buffer.AddRange(wrkByte);
msBuffer.Write(buff, 0, bytesRead);
remainToRead -= bytesRead;
}
//} while (buffer.Count < ln && bytesRead > 0);
} while (msBuffer.Length < ln && bytesRead > 0);
if (bytesRead > 0)
{
//RaiseBytesReceived(buffer.ToArray());
msBuffer.Position = 0;
RaiseBytesReceived(msBuffer);
}
}
}
else
{
Abort = true;
mreSender.Set();
}
}
} while (!Abort);
}
catch (ObjectDisposedException)
{
}
catch (ThreadAbortException)
{
}
catch (System.IO.IOException)
{
//RaiseExceptionEncountered(e);
}
catch (System.Net.Sockets.SocketException e)
{
RaiseExceptionEncountered(e);
}
if (this.ConnectionLost != null)
{
ConnectionLost(this, new ConnectionEventArgs(this.ID));
}
}