public override void SessionReceive(IServer server, SessionReceiveEventArgs e)
{
//类似于实现ReadBytes(byte[] eof)
var data= e.Stream.ToPipeStream().ReadBytes(new byte[] { 0x0D, 0x0A });
//.........
}
/// <summary>
/// 读取字节数据
/// </summary>
/// <returns></returns>
public byte[] ReadBytes(int length)
{
if (length == 0)
return new byte[0];
IBuffer rbuffer;
//暂时不考虑跨平台的代码兼容
ArraySegment<byte> data;
byte[] byteSpan = mCacheBlock;
//要获取的长度小于缓存固定长度时处理的逻辑
if (length < mCacheBlockLen)
{
rbuffer = GetAndVerifyReadBuffer();
int freelen = rbuffer.Length - rbuffer.Postion;
if (freelen > length)
{
data = rbuffer.Read(length);
ReadAdvance(length);
return data.Array;
}
}
int rlen = 0;
while (length > 0)
{
if (length > mCacheBlockLen)
rlen = mCacheBlockLen;
else
rlen = length;
rbuffer = GetAndVerifyReadBuffer();
int freelen = rbuffer.Length - rbuffer.Postion;
if (freelen > rlen)
{
data = rbuffer.Read(rlen);
}
else
{
data = rbuffer.Read(freelen);
}
ReadAdvance(data.Count);
length -= data.Count;
}
return data.Array;
}
/// <summary>
/// 尝试读取数据
/// </summary>
/// <param name="eof">结束标识</param>
/// <param name="value">读取到的byte[]数据</param>
/// <param name="returnEof">返回时是否包含结束标识</param>
/// <returns></returns>
public bool TryReadWith(byte[] eof, out byte[] value, bool returnEof = false)
{
value = new byte[0];
IndexOfResult result = IndexOf(eof);
int length = result.Length;
value = new byte[length];
if (result.End != null)
{
if (result.Start.ID == result.End.ID)
{
if (result.Length < mCacheBlockLen)
{
Array.Copy(result.Start.Bytes,0, value, 0, length);
ReadFree(length);
}
else
{
value = ReadBytes(length);
}
}
else
{
if (returnEof)
{
value = ReadBytes(result.Length);
}
else
{
value = ReadBytes(result.Length - eof.Length);
Read(eof, 0, eof.Length);
}
}
return true;
}
return false;
}
public override void SessionReceive(IServer server, SessionReceiveEventArgs e)
{
byte[] result;
if (e.Stream.ToPipeStream().TryReadWith(new byte[] { 0x0D, 0x0A },out result,true))
{
if (result[0] == 0xFA && result.Length == 14 )
{
Console.WriteLine("获取得到了设备代码数据!");
}
}
}