// 3 types of read
// 1) To some terminator
// 2) Specified length
// 3) While socket is closed with ShutDown
#region method ReadData (terminator)
/// <summary>
/// Reads data from socket while specified terminator is reached.
/// If maximum length is exceeded, reading continues but data won't be stored to stream.
/// </summary>
/// <param name="storeStream">Stream where to store readed data.</param>
/// <param name="maxLength">Maximum length to read.</param>
/// <param name="terminator">Terminator which trminates reading.</param>
/// <param name="removeFromEnd">Part of trminator what to remove from end. Can be empty or max part is terminator.</param>
/// <returns></returns>
public ReadReplyCode ReadData(Stream storeStream, long maxLength, string terminator, string removeFromEnd)
{
if (storeStream == null)
{
throw new Exception("Parameter storeStream can't be null !");
}
ReadReplyCode replyCode = ReadReplyCode.Ok;
try{
_FixedStack stack = new _FixedStack(terminator);
long readedCount = 0;
int nextReadWriteLen = 1;
while (nextReadWriteLen > 0)
{
//Read byte(s)
byte[] b = new byte[nextReadWriteLen];
int countRecieved = this.Receive(b);
if (countRecieved > 0)
{
readedCount += countRecieved;
// Write byte(s) to buffer, if length isn't exceeded.
if (readedCount <= maxLength)
{
storeStream.Write(b, 0, countRecieved);
}
// Write to stack(terminator checker)
nextReadWriteLen = stack.Push(b, countRecieved);
}
// Client disconnected
else
{
return(ReadReplyCode.SocketClosed);
}
OnActivity();
}
// Check if length is exceeded
if (readedCount > maxLength)
{
return(ReadReplyCode.LengthExceeded);
}
// If reply is ok then remove chars if any specified by 'removeFromEnd'.
if (replyCode == ReadReplyCode.Ok && removeFromEnd.Length > 0)
{
storeStream.SetLength(storeStream.Length - removeFromEnd.Length);
}
// Logging stuff
if (m_pLogger != null)
{
if (storeStream is MemoryStream && storeStream.Length < 200)
{
MemoryStream ms = (MemoryStream)storeStream;
m_pLogger.AddReadEntry(m_pEncoding.GetString(ms.ToArray()));
}
else
{
m_pLogger.AddReadEntry("Big binary, readed " + readedCount.ToString() + " bytes.");
}
}
}
catch (Exception x) {
replyCode = ReadReplyCode.UnKnownError;
if (x is SocketException)
{
SocketException xS = (SocketException)x;
if (xS.ErrorCode == 10060)
{
return(ReadReplyCode.TimeOut);
}
}
}
return(replyCode);
}