Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created November 27, 2014 23:34
Show Gist options
  • Save AlexArchive/1fb01318d344a3db9ee6 to your computer and use it in GitHub Desktop.
Save AlexArchive/1fb01318d344a3db9ee6 to your computer and use it in GitHub Desktop.
class Program
{
static void Main(string[] args)
{
// The message you want to send accross the network
var outboundMessage = new ChatMessage { Body = "Hello" };
// Serialize the outbound message
byte[] outboundMessageData;
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, outboundMessage);
outboundMessageData = stream.ToArray();
}
// Imagine you issue a network read and hydrate outboundMessageData
// Deserialize the message
object inboundMessage;
using (var stream = new MemoryStream(outboundMessageData))
{
var formatter = new BinaryFormatter();
inboundMessage = formatter.Deserialize(stream);
}
// Branch accordingly..
if (inboundMessage.GetType() == typeof(ChatMessage))
{
var chatMessage = (ChatMessage) inboundMessage;
Console.WriteLine(chatMessage.Body);
}
}
}
[Serializable]
public class ChatMessage
{
public string Body { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment