对于网络通信有所了解的都应该知道,数据在网络传输的格式必须以字节流的形式进行,那么免不了要对字节流进行写入和读出操作,为了方便后面的操作,我们有必要封装一个读写字节流的操作类,在这里我定义了一个字节流的操作类ByteBuffer类,用于将各个类型数据写入流中,也可从字节流中读取各种类型的数据:
using System.IO;
using System.Text;
using System;
namespace Net {
public class ByteBuffer {
MemoryStream stream = null;
BinaryWriter writer = null;
BinaryReader reader = null;
public ByteBuffer() {
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}
public ByteBuffer(byte[] data) {
if (data != null) {
stream = new MemoryStream(data);
reader = new BinaryReader(stream);
} else {
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}
}
public void Close() {
if (writer != null) writer.Close();
if (reader != null) reader.Close();
stream.Close();
writer = null;
reader = null;
stream = null;
}
public void WriteByte(byte v) {
writer.Write(v);
}
public void WriteInt(int v) {
writer.Write((int)v);
}
public void WriteShort(ushort v) {
writer.Write((ushort)v);
}
public void WriteLong(long v) {
writer.Write((long)v);
}
public void WriteFloat(float v) {
byte[] temp = BitConverter.GetBytes(v);
Array.Reverse(temp);
writer.Write(BitConverter.ToSingle(temp, 0));
}
public void WriteDouble(double v) {
byte[] temp = BitConverter.GetBytes(v);
Array.Reverse(temp);
writer.Write(BitConverter.ToDouble(temp, 0));
}
public void WriteString(string v) {
byte[] bytes = Encoding.UTF8.GetBytes(v);
writer.Write((ushort)bytes.Length);
writer.Write(bytes);
}
public void WriteBytes(byte[] v) {
writer.Write((int)v.Length);
writer.Write(v);
}
public byte ReadByte() {
return reader.ReadByte();
}
public int ReadInt() {
return (int)reader.ReadInt32();
}
public ushort ReadShort() {
return (ushort)reader.ReadInt16();
}
public long ReadLong() {
return (long)reader.ReadInt64();
}
public float ReadFloat() {
byte[] temp = BitConverter.GetBytes(reader.ReadSingle());
Array.Reverse(temp);
return BitConverter.ToSingle(temp, 0);
}
public double ReadDouble() {
byte[] temp = BitConverter.GetBytes(reader.ReadDouble());
Array.Reverse(temp);
return BitConverter.ToDouble(temp, 0);
}
public string ReadString() {
ushort len = ReadShort();
byte[] buffer = new byte[len];
buffer = reader.ReadBytes(len);
return Encoding.UTF8.GetString(buffer);
}
public byte[] ReadBytes() {
int len = ReadInt();
return reader.ReadBytes(len);
}
public byte[] ToBytes() {
writer.Flush();
return stream.ToArray();
}
public void Flush() {
writer.Flush();
}
}
}
使用此操作类进行读写数据的操作范例如下:
- 读取数据:
//result是字节数组byte[],从中读取两个int类型的数据
ByteBuffer buff = new ByteBuffer(result);
int len = buff.ReadShort();
int protoId = buff.ReadShort();
- 写入数据:
//result是字节数组byte[],从写入两个不同类型的数据
ByteBuffer buff = new ByteBuffer();
int protoId = ProtoDic.GetProtoIdByProtoType(0);
buff.WriteShort((ushort)protoId);
buff.WriteBytes(ms.ToArray());
byte[] result = buff.ToBytes();