Skip to content

Instantly share code, notes, and snippets.

@rdeioris
Created February 18, 2019 19:07
Show Gist options
  • Save rdeioris/93d79e99c1e5723f3cd62d4990ab58d9 to your computer and use it in GitHub Desktop.
Save rdeioris/93d79e99c1e5723f3cd62d4990ab58d9 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
public class Packet
{
private MemoryStream stream;
private BinaryWriter writer;
private static uint packetCounter;
private uint id;
public uint Id
{
get
{
return id;
}
}
public Packet()
{
stream = new MemoryStream();
writer = new BinaryWriter(stream);
id = ++packetCounter;
}
public Packet(byte command, params object[] elements) : this()
{
// first element is always the command
writer.Write(command);
foreach (object element in elements)
{
if (element is int)
{
writer.Write((int)element);
}
else if (element is float)
{
writer.Write((float)element);
}
else if (element is byte)
{
writer.Write((byte)element);
}
else if (element is char)
{
writer.Write((char)element);
}
else if (element is uint)
{
writer.Write((uint)element);
}
else
{
throw new Exception("unknown type");
}
}
}
public byte[] GetData()
{
return stream.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment