Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- public static class SocketSerialization
- {
- public static SocketMessageData Serialize(object obj)
- {
- using (var memoryStream = new MemoryStream())
- {
- new BinaryFormatter().Serialize(memoryStream, obj);
- var data = new SocketMessageData {TotalSize = (int)memoryStream.Length};
- data.Bytes = new byte[data.TotalSize + 4];
- var lengthBytes = BitConverter.GetBytes(data.TotalSize);
- Array.Copy(lengthBytes, data.Bytes, lengthBytes.Length);
- Array.Copy(memoryStream.ToArray(), 0, data.Bytes, lengthBytes.Length, data.TotalSize);
- return data;
- }
- }
- public static object Deserialize(SocketMessageData message)
- {
- using (var memoryStream = new MemoryStream(message.Bytes))
- {
- return new BinaryFormatter().Deserialize(memoryStream);
- }
- }
- public class SocketMessageData
- {
- public int TotalSize;
- public byte[] Bytes = new byte[0];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement