byte[] tmpaa = new byte[1]; //先定义一个全局变量,保存第一次接受的字头,因为第一次接受就是一个字节,这个字节是下次接受的字头
bool isTou = false;//判断是不是第一次接受的字节,是的话,赋值给第二次接受的字节
public string Readconn(SocketAsyncEventArgs e)
{
byte[] tmpa = new byte[e.BytesTransferred];
if (tmpa.Length == 1)
{
isTou = true;
tmpaa[0] = e.Buffer[0];
return "cuowu";
}
else
{
string resRead = "";
for (int i = 1; i < e.BytesTransferred; i++)
{
if (isTou)
{
tmpa[0] = tmpaa[0];
tmpa[1] = tmpaa[0];
isTou = false;
}
tmpa[i] = e.Buffer[i - 1];
}
System.IO.Stream connection = new System.IO.MemoryStream(tmpa);
List<string> output = new List<string>();
string o = "";
byte[] tmp = new byte[4];
long count;
while (true)
{
tmp[3] = (byte)connection.ReadByte();
//if(tmp[3] == 220) tmp[3] = (byte)connection.ReadByte(); it sometimes happend to me that
//mikrotik send 220 as some kind of "bonus" between words, this fixed things, not sure about it though
if (tmp[3] == 255)
{
output.Add(o);
if (o.Substring(0, 5) == "!done" || o.Substring(0, 3) == "!re")
{
break;
}
else
{
o = "";
continue;
}
}
else
{
if (tmp[3] < 0x80)
{
count = tmp[3];
}
else
{
if (tmp[3] < 0xC0)
{
int tmpi = BitConverter.ToInt32(new byte[] { (byte)connection.ReadByte(), tmp[3], 0, 0 }, 0);
count = tmpi ^ 0x8000;
}
else
{
if (tmp[3] < 0xE0)
{
tmp[2] = (byte)connection.ReadByte();
int tmpi = BitConverter.ToInt32(new byte[] { (byte)connection.ReadByte(), tmp[2], tmp[3], 0 }, 0);
count = tmpi ^ 0xC00000;
}
else
{
if (tmp[3] < 0xF0)
{
tmp[2] = (byte)connection.ReadByte();
tmp[1] = (byte)connection.ReadByte();
int tmpi = BitConverter.ToInt32(new byte[] { (byte)connection.ReadByte(), tmp[1], tmp[2], tmp[3] }, 0);
count = tmpi ^ 0xE0000000;
}
else
{
if (tmp[3] == 0xF0)
{
tmp[3] = (byte)connection.ReadByte();
tmp[2] = (byte)connection.ReadByte();
tmp[1] = (byte)connection.ReadByte();
tmp[0] = (byte)connection.ReadByte();
count = BitConverter.ToInt32(tmp, 0);
}
else
{
//Error in packet reception, unknown length
break;
}
}
}
}
}
}
for (int i = 0; i < count; i++)
{
o += (Char)connection.ReadByte();
}
}
foreach (string item in output)
{
resRead += item;
}
//output.Clear();
return resRead;
}
}