データの取り扱いが簡単になるPacketクラス

使用するメリット

データの終端など意識することなく読み書きが可能

デメリット

少ないデータのやり取りでは逆にデータ量が増える

public enum PacketType {
  BINARY,
  META,
  KEEP
}

public class Packet {
  public Packet(PacketType type, byte[] data)
        {
            this.Type = type;
            this.Data = data;
        }

        public PacketType Type { get; protected set; }
        public byte[] Data { get; protected set; }

        public int BinarySize
        {
            get
            {
                return Data.Length;
            }
        }
}

public class PacketWriter {
  public PacketWriter(Stream stream) {
    this.stream = stream;
  }
  private Stream stream;
  public Packet Read() {
    byte[] sof = new byte[4];
    int ty;
    byte[] buffer;
    stream.Read(sof, 0, sof.Length);
    ty = stream.ReadByte();
    int size = BitConverter.ToInt32(sof, 0);
    buffer = new byte[size];
    stream.Read(buffer, 0, size);
    PacketType type = (PacketType) ty;
    return new Packet(type, buffer);
  }
  public void Write(Packet packet) {
    int size = packet.Data.Length;
    byte[] sof = BitConverter.GetBytes(size);
    byte type = (byte) packet.Type;
    stream.Write(sof, 0, sof.Length);
    stream.WriteByte(type);
    stream.Write(packet.Data, 0, size);
  }
}

投稿者:

kema

趣味でプログラミングしてるだけの人

コメントを残す