Skip to content

Instantly share code, notes, and snippets.

@an-roo
Created November 29, 2010 05:48
Show Gist options
  • Select an option

  • Save an-roo/719624 to your computer and use it in GitHub Desktop.

Select an option

Save an-roo/719624 to your computer and use it in GitHub Desktop.
public class SerializerHelper
{
SerializerHelper()
{
}
public static void serializeToStream(System.IO.Stream stream, object obj)
{
if (obj == null)
return;
INetPacket inp = (INetPacket)obj;
try
{
lock (stream)
{
BinaryFormatter bformatter = new BinaryFormatter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bformatter.Serialize(ms, obj);
int lengthOfStream = Convert.ToInt32(ms.Length);
stream.Write(new byte[] { 0xAA, 0xBB, 0xCC }, 0, 3);
stream.Write(BitConverter.GetBytes(lengthOfStream), 0, 4);
stream.Write(ms.ToArray(), 0, lengthOfStream);
//stream.Flush();
}
}
catch(Exception e)
{
}
}
public static INetPacket deserialize(TcpClient tcp1)
{
INetPacket inp;
try
{
lock (tcp1.GetStream())
{
BinaryFormatter bformatter = new BinaryFormatter();
bool continueMe = false;
while (continueMe == false)
{
int byte1 = tcp1.GetStream().ReadByte();
if (byte1 == 0xAA)
{
int byte2 = tcp1.GetStream().ReadByte();
if (byte2 == 0xBB)
{
int byte3 = tcp1.GetStream().ReadByte();
if (byte3 == 0xCC)
{
continueMe = true;
}
}
}
}
byte[] incomingLength = new byte[4];
tcp1.GetStream().Read(incomingLength, 0, 4);
int lengthOfStream = BitConverter.ToInt32(incomingLength, 0);
DateTime now = DateTime.Now;
while (tcp1.Available < lengthOfStream && now + TimeSpan.FromMilliseconds(1000) > DateTime.Now)
{
System.Threading.Thread.Sleep(50);
}
if (tcp1.Available >= lengthOfStream)
{
return (INetPacket)bformatter.Deserialize(tcp1.GetStream());
}
Console.WriteLine("Ugh.");
}
}
catch
{
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment