Advertisement
Guest User

Untitled

a guest
May 24th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4.  
  5. public static class SocketSerialization
  6. {
  7.     public static SocketMessageData Serialize(object obj)
  8.     {
  9.         using (var memoryStream = new MemoryStream())
  10.         {
  11.             new BinaryFormatter().Serialize(memoryStream, obj);
  12.             var data = new SocketMessageData {TotalSize = (int)memoryStream.Length};
  13.             data.Bytes = new byte[data.TotalSize + 4];
  14.             var lengthBytes = BitConverter.GetBytes(data.TotalSize);
  15.             Array.Copy(lengthBytes, data.Bytes, lengthBytes.Length);
  16.             Array.Copy(memoryStream.ToArray(), 0, data.Bytes, lengthBytes.Length, data.TotalSize);
  17.             return data;
  18.         }
  19.     }
  20.  
  21.     public static object Deserialize(SocketMessageData message)
  22.     {
  23.         using (var memoryStream = new MemoryStream(message.Bytes))
  24.         {
  25.             return new BinaryFormatter().Deserialize(memoryStream);
  26.         }
  27.     }
  28.  
  29.     public class SocketMessageData
  30.     {
  31.         public int TotalSize;
  32.         public byte[] Bytes = new byte[0];
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement