//添加字符串
public void AddString(string str)
{
Int32 len = str.Length;
byte[] lenBytes = BitConverter.GetBytes (len);
//byte[] strBytes = System.Text.Encoding.UTF8.GetBytes (str);
Encoding gb2312= System.Text.Encoding.GetEncoding(936);
byte[] strBytes = gb2312.GetBytes(str);
if(bytes == null)
bytes = lenBytes.Concat(strBytes).ToArray();
else
bytes = bytes.Concat(lenBytes).Concat(strBytes).ToArray();
}
//从字节数组的start处开始读取字符串
public string GetString(int start, ref int end)
{
if (bytes == null)
return "";
if (bytes.Length < start + sizeof(Int32))
return "";
Int32 strLen = BitConverter.ToInt32 (bytes, start);
if (bytes.Length < start + sizeof(Int32) + strLen)
return "";
string str = System.Text.Encoding.UTF8.GetString(bytes,start + sizeof(Int32),strLen);
end = start + sizeof(Int32) + strLen;
return str;
}
我用的是Socket服务器,当客户端发送汉字类型的字符串的时候服务器端就会报错,字母和数字就没问题