// --------------------------------------------------------------------- // This is our client task // It connects to the server, and then sends a request once per second // It collects responses as they arrive, and it prints them out. We will // run several client tasks in parallel, each with a different random ID. public static void ClientTask() { using (var context = ZmqContext.Create()) { using (ZmqSocket client = context.CreateSocket(SocketType.DEALER)) { // Generate printable identity for the client ZHelpers.SetID(client, Encoding.Unicode); string identity = Encoding.Unicode.GetString(client.Identity); client.Connect("tcp://localhost:5570"); client.ReceiveReady += (s, e) => { var zmsg = new ZMessage(e.Socket); Console.WriteLine("{0} : {1}", identity, zmsg.BodyToString()); }; int requestNumber = 0; var poller = new Poller(new List<ZmqSocket> { client }); while (true) { // Tick once per second, pulling in arriving messages for (int centitick = 0; centitick < 100; centitick++) { poller.Poll(TimeSpan.FromMilliseconds(10000)); } var zmsg = new ZMessage(""); zmsg.StringToBody(String.Format("request: {0}", ++requestNumber)); zmsg.Send(client); } } } }
// --------------------------------------------------------------------- // This is our client task // It connects to the server, and then sends a request once per second // It collects responses as they arrive, and it prints them out. We will // run several client tasks in parallel, each with a different random ID. public static void ClientTask() { using (var context = ZmqContext.Create()) { using (ZmqSocket client = context.CreateSocket(SocketType.DEALER)) { // Generate printable identity for the client string identity = ZHelpers.SetID(client, Encoding.Unicode); //client.Connect("tcp://localhost:5570"); string serviceRepoAddress = ConfigurationSettings.AppSettings["serviceRepoAddressZMQ"]; client.Connect(serviceRepoAddress); client.ReceiveReady += (s, e) => { var zmsg = new ZMessage(e.Socket); Console.WriteLine("{0} : {1}", identity, zmsg.BodyToString()); }; int requestNumber = 0; var poller = new Poller(new List<ZmqSocket> { client }); var zmsg2 = new ZMessage(""); JSONMessage jsonMess = new JSONMessage(); jsonMess.Service = "Klient"; jsonMess.Function = "RegisterService"; jsonMess.Parameters = new string[] { "Klient", "Location", "binding" }; string json = JsonConvert.SerializeObject(jsonMess); zmsg2.StringToBody(json); zmsg2.Send(client); while (true) { // Tick once per second, pulling in arriving messages for (int centitick = 0; centitick < 100; centitick++) { poller.Poll(TimeSpan.FromMilliseconds(10)); } var zmsg = new ZMessage(""); jsonMess = new JSONMessage(); jsonMess.Service = "Klient"; jsonMess.Function = "GetServiceLocation"; jsonMess.Parameters = new string[] { "Klient", "binding" }; json = JsonConvert.SerializeObject(jsonMess); zmsg.StringToBody(json); zmsg.Send(client); } } } }
static void Main(string[] args) { using (var context = ZmqContext.Create()) { using (var worker = context.CreateSocket(SocketType.REQ)) { var randomizer = new Random(DateTime.Now.Millisecond); var identity = ZHelpers.SetID(worker, Encoding.Unicode); worker.Connect("tcp://localhost:5556"); Console.WriteLine("I: {0} worker ready", identity); worker.Send("READY", Encoding.Unicode); var cycles = 0; while (true) { var zmsg = new ZMessage(worker); cycles += 1; if (cycles > 3 && randomizer.Next(0, 5) == 0) { Console.WriteLine("I: {0} simulating a crash", identity); break; } else if (cycles > 3 && randomizer.Next(0, 5) == 0) { Console.WriteLine("I: {0} simulating CPU overload", identity); System.Threading.Thread.Sleep(3000); } Console.WriteLine("I: {0} normal reply", identity); System.Threading.Thread.Sleep(1000); zmsg.Send(worker); } } } }
// Accept a request and reply with the same text a random number of // times, with random delays between replies. private static void ServerWorker(object context) { var randomizer = new Random(DateTime.Now.Millisecond); using (ZmqSocket worker = ((ZmqContext)context).CreateSocket(SocketType.DEALER)) { worker.Connect("inproc://backend"); while (true) { // The DEALER socket gives us the address envelope and message var zmsg = new ZMessage(worker); // Send 0..4 replies back int replies = randomizer.Next(5); for (int reply = 0; reply < replies; reply++) { Thread.Sleep(randomizer.Next(1, 1000)); zmsg.Send(worker); } } } }
// --------------------------------------------------------------------- // This is our server task // It uses the multithreaded server model to deal requests out to a pool // of workers and route replies back to clients. One worker can handle // one request at a time but one client can talk to multiple workers at // once. private static void ServerTask() { var workers = new List<Thread>(5); using (var context = ZmqContext.Create()) { using (ZmqSocket frontend = context.CreateSocket(SocketType.ROUTER), backend = context.CreateSocket(SocketType.DEALER)) { frontend.Bind("tcp://*:5570"); backend.Bind("inproc://backend"); for (int workerNumber = 0; workerNumber < 5; workerNumber++) { workers.Add(new Thread(ServerWorker)); workers[workerNumber].Start(context); } // Switch messages between frontend and backend frontend.ReceiveReady += (s, e) => { var zmsg = new ZMessage(e.Socket); zmsg.Send(backend); }; backend.ReceiveReady += (s, e) => { var zmsg = new ZMessage(e.Socket); zmsg.Send(frontend); }; var poller = new Poller(new List<ZmqSocket> { frontend, backend }); while (true) { poller.Poll(); } } } }
public static void Main(string[] args) { var workers = new List<Thread>(); var clients = new List<Thread>(); // Prepare our context and sockets using (var ctx = ZmqContext.Create()) { using (ZmqSocket frontend = ctx.CreateSocket(SocketType.ROUTER), backend = ctx.CreateSocket(SocketType.ROUTER)) { frontend.Bind("tcp://*:5555"); backend.Bind("tcp://*:5556"); int clientId; for (clientId = 0; clientId < Program.clients; clientId++) { clients.Add(new Thread(ClientTask)); clients[clientId].Start(); } for (int workerId = 0; workerId < Program.workers; workerId++) { workers.Add(new Thread(WorkerTask)); workers[workerId].Start(); } // Logic of LRU loop // - Poll backend always, frontend only if 1+ worker ready // - If worker replies, queue worker as ready and forward reply // to client if necessary // - If client requests, pop next worker and send request to it // Queue of available workers var workerQueue = new Queue<byte[]>(); // Handle worker activity on backend backend.ReceiveReady += (socket, revents) => { var zmsg = new ZMessage(revents.Socket); // Use worker address for LRU routing workerQueue.Enqueue(zmsg.Unwrap()); // Forward message to client if it's not a READY if (!Encoding.Unicode.GetString(zmsg.Address).Equals("READY")) { zmsg.Send(frontend); } }; frontend.ReceiveReady += (socket, revents) => { // Now get next client request, route to next worker // Dequeue and drop the next worker address var zmsg = new ZMessage(revents.Socket); zmsg.Wrap(workerQueue.Dequeue(), new byte[0]); zmsg.Send(backend); }; var poller = new Poller(new List<ZmqSocket>{ frontend, backend }); while (true) { //int rc = context.Poller(workerQueue.Count > 0 // ? new List<ZmqSocket>(new ZmqSocket[] {frontend, backend}) // : new List<ZmqSocket>(new ZmqSocket[] {backend})); int rc = poller.Poll(); if (rc == -1) { break; } } } } }
private static void WorkerTask() { using (var ctx = ZmqContext.Create()) { using (var worker = ctx.CreateSocket(SocketType.REQ)) { ZHelpers.SetID(worker, Encoding.Unicode); worker.Connect("tcp://localhost:5556"); // Tell broker we're ready for work worker.Send("READY", Encoding.Unicode); while (true) { var zmsg = new ZMessage(worker); Console.WriteLine("Worker: {0}", Encoding.Unicode.GetString(zmsg.Body)); zmsg.StringToBody("OK"); zmsg.Send(worker); } } } }
// --------------------------------------------------------------------- // This is our server task // It uses the multithreaded server model to deal requests out to a pool // of workers and route replies back to clients. One worker can handle // one request at a time but one client can talk to multiple workers at // once. private static void ServerTask() { var workers = new List<Thread>(5); using (var context = ZmqContext.Create()) { using (ZmqSocket frontend = context.CreateSocket(SocketType.ROUTER), backend = context.CreateSocket(SocketType.DEALER)) { frontend.Bind("tcp://*:5570"); backend.Bind("inproc://backend"); for (int workerNumber = 0; workerNumber < 5; workerNumber++) { workers.Add(new Thread(ServerWorker)); workers[workerNumber].Start(context); } // Switch messages between frontend and backend frontend.ReceiveReady += (s, e) => { var zmsg = new ZMessage(e.Socket); zmsg.Send(backend); }; backend.ReceiveReady += (s, e) => { var zmsg = new ZMessage(e.Socket); string lol = zmsg.BodyToString(); JSONMessage m = JsonConvert.DeserializeObject<JSONMessage>(lol); if (m.Function != null) { switch (m.Function) { case "RegisterService": Console.WriteLine("ZEROMQ RegisterService: " + m.Parameters[0] + ";" + m.Parameters[1] + ";" + m.Parameters[2]); m.ReponseString = "OK"; Repository.RegisterService(m.Parameters[0], m.Parameters[1], m.Parameters[2]); break; case "GetServiceLocation": Console.WriteLine("ZEROMQ GetServiceLocation: " + m.Parameters[0] + ";" + m.Parameters[1]); string locat = Repository.GetServiceLocation(m.Parameters[0], m.Parameters[1]); m.ReponseString = locat; break; case "Alive": Console.WriteLine("ZEROMQ Alive: " + ";" + m.Parameters[0] + m.Parameters[1]); Repository.Alive(m.Parameters[0], m.Parameters[1]); m.ReponseString = "OK"; break; case "Unregister": Console.WriteLine("ZEROMQ Unregister: " + ";" + m.Parameters[0] + m.Parameters[1]); Repository.Unregister(m.Parameters[0], m.Parameters[1]); m.ReponseString = "OK"; break; default: Console.WriteLine("Unknown: " + m.Function); break; } } m.Service = "IServiceRepository"; string json = JsonConvert.SerializeObject(m); zmsg.StringToBody(json); zmsg.Send(frontend); }; var poller = new Poller(new List<ZmqSocket> { frontend, backend }); while (true) { poller.Poll(); } } } }
static void Main(string[] args) { using (var context = ZmqContext.Create()) { int interval = INTERVAL_INIT; int liveness = HEARTBEAT_LIVENESS; while (true) { int cylces = 0; using (ZmqSocket worker = ConnectWorker(context)) { worker.ReceiveReady += (socket, revents) => { var zmsg = new ZMessage(revents.Socket); byte[] identity = zmsg.Unwrap(); switch (Encoding.Unicode.GetString(zmsg.Address)) { case PPP_HEARTBEAT: interval = INTERVAL_INIT; liveness = HEARTBEAT_LIVENESS; break; default: if (zmsg.FrameCount > 1) { if (!doTheWork(cylces++)) { break; } interval = INTERVAL_INIT; liveness = HEARTBEAT_LIVENESS; Console.WriteLine("W: work completed"); zmsg.Send(worker); } else { Console.WriteLine("E: invalied message {0}", identity); } break; }; }; //Send out heartbeats at regular intervals DateTime heartbeat_at = DateTime.Now.AddMilliseconds(HEARTBEAT_INTERVAL); while (true) { var poller = new Poller(new List<ZmqSocket> { worker }); poller.Poll(TimeSpan.FromMilliseconds(HEARTBEAT_INTERVAL * 1000)); //If liveness hits zero, queue is considered disconnected if (--liveness <= 0) { Console.WriteLine("W: heartbeat failure, can't reach queue."); Console.WriteLine("W: reconnecting in {0} msecs...", interval); try { Thread.Sleep(interval); } catch (System.Exception ex) { Console.WriteLine(ex.Message); } //Exponential Backoff if (interval < INTERVAL_MAX) interval *= 2; liveness = HEARTBEAT_LIVENESS; //Break the while loop and start the connection over break; } //Send heartbeat to queue if it's time if (DateTime.Now > heartbeat_at) { heartbeat_at = DateTime.Now.AddMilliseconds(HEARTBEAT_INTERVAL); ZMessage zmsg = new ZMessage(PPP_HEARTBEAT); zmsg.Send(worker); } } } } } }