Skip to content

Instantly share code, notes, and snippets.

@SneakyBrian
Created October 9, 2012 22:13
Show Gist options
  • Save SneakyBrian/3861775 to your computer and use it in GitHub Desktop.
Save SneakyBrian/3861775 to your computer and use it in GitHub Desktop.
ZeroMQ MsgPack .NET Testbed
using System;
using System.IO;
using MsgPack.Serialization;
using ZeroMQ_MessagePack_Testbed.Models;
using ZMQ;
namespace ZeroMQ_MessagePack_Testbed
{
class Program
{
static void Main(string[] args)
{
using (var context = new Context(1))
{
using (var subscriber = context.Socket(SocketType.SUB))
{
subscriber.Subscribe(new byte[] { 7, 7, 7, 7 });
subscriber.Connect("tcp://localhost:5556");
var serializer = MessagePackSerializer.Create<Message>();
while (true)
{
var response = subscriber.Recv();
using (var messageStream = new MemoryStream(response))
{
//trim the 4 byte header off
messageStream.Seek(4, SeekOrigin.Begin);
//deserialize from the stream
var message = serializer.Unpack(messageStream);
Console.WriteLine("CLIENT: {0} {1} {2}", message.Id, message.Timestamp, DateTime.UtcNow);
}
}
}
}
}
}
}
using System;
namespace ZeroMQ_MessagePack_Testbed.Models
{
public class Message
{
public Guid Id;
public Priority Priority;
public string Subject;
public string Body;
public DateTime Timestamp;
}
public enum Priority
{
High,
Medium,
Low
}
}
using System;
using System.IO;
using System.Threading;
using MsgPack.Serialization;
using ZeroMQ_MessagePack_Testbed.Models;
using ZMQ;
namespace ZeroMQ_MessagePack_Testbed.Server
{
class Program
{
static void Main(string[] args)
{
using (var context = new Context(1))
{
using (var publisher = context.Socket(SocketType.PUB))
{
publisher.Bind("tcp://*:5556");
var randomizer = new Random(DateTime.Now.Millisecond);
var serializer = MessagePackSerializer.Create<Message>();
while (true)
{
Thread.Sleep(500);
var message = new Message
{
Id = Guid.NewGuid(),
Priority = Priority.Medium,
Subject = "Test Message" + randomizer.Next(0, 100),
Body = "This is a test message " + randomizer.Next(0, 100000),
Timestamp = DateTime.UtcNow
};
Console.WriteLine("SERVER: {0} {1}", message.Id, message.Timestamp);
using (var messageStream = new MemoryStream())
{
//write 4 byte client id first
messageStream.Write(new byte[] { 7, 7, 7, 7 }, 0, 4);
//write the packed message to the stream
serializer.Pack(messageStream, message);
// Send message to 0..N subscribers via a pub socket
publisher.Send(messageStream.GetBuffer());
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment