Skip to content

Instantly share code, notes, and snippets.

@rkrishnasanka
Created November 21, 2014 01:59
Show Gist options
  • Save rkrishnasanka/97ae9c5083adecb4d63b to your computer and use it in GitHub Desktop.
Save rkrishnasanka/97ae9c5083adecb4d63b to your computer and use it in GitHub Desktop.
Generic Packet Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Packet
{
// ----------------
// Packet Structure
// ----------------
// Description -> |timestamp |message |
// Size in bytes -> |sizeoflong | sizeofuint |
public uint message { get; set; }
public long timestamp { get; set; }
public Packet()
{
this.timestamp = DateTime.Now.Ticks;
}
public Packet(byte[] dataStream)
{
var startindex = 0;
this.timestamp = long.Parse(Encoding.UTF8.GetString(dataStream, startindex, sizeof(long)));
startindex += sizeof(long);
// Read the length of the message (4 bytes)
this.timestamp = uint.Parse(Encoding.UTF8.GetString(dataStream, startindex, sizeof(uint)));
}
public byte[] GetDataStream()
{
var timestampbytes = BitConverter.GetBytes(this.timestamp);
var messagebytes = BitConverter.GetBytes(this.message);
byte[] dataStream = new byte[timestampbytes.Length + messagebytes.Length];
Buffer.BlockCopy(timestampbytes, 0, dataStream, 0, timestampbytes.Length);
Buffer.BlockCopy(messagebytes, 0, dataStream, timestampbytes.Length, messagebytes.Length);
return dataStream;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment