日期:2014-05-19  浏览次数:20896 次

弱问socket发送Byte[]的问题
就是把消息组成一个包再发送,避免“粘包”。
想发的消息就是Byte[]   aa,   怎样给aa添加一个起始标记和长度呢,我希望长度是ushort.想麻烦老手告知定义包头的代码.谢谢啊!

Byte[]   aa=System.Text.Encoding.ASCII.GetBytes( "hello ");


------解决方案--------------------
这是我一个用来处理封包的类!
public struct Message
{
public byte Class;
public byte Flag;
public int Size;
public byte[] Content;

public byte[] ToBytes()
{
byte[] _arr = new byte[Size + 6];
_arr[0] = Class;
_arr[1] = Flag;
Buffer.BlockCopy(CommonFunc.Int32ToByte(Size), 0, _arr, 2, 4);
if (Size > 0)//CommonFunc.Int32ToByte(Size)请用Convert.ToBytes()代替!
Array.Copy(Content, 0, _arr, 6, Size);
return _arr;
}

public static Message FromBytes(byte[] Buffer)
{
Message message = new Message();
using (System.IO.MemoryStream mem = new System.IO.MemoryStream(Buffer))
{
BinaryReader reader = new BinaryReader(mem);
message.Class = reader.ReadByte();
message.Flag = reader.ReadByte();
message.Size = reader.ReadInt32();
message.Content = reader.ReadBytes(message.Size);
}
return message;
}
}