static void Espresso0_Listener(ZContext context) { // The listener receives all messages flowing through the proxy, on its // pipe. In CZMQ, the pipe is a pair of ZMQ_PAIR sockets that connect // attached child threads. In other languages your mileage may vary: using (var listener = new ZSocket(context, ZSocketType.PAIR)) { listener.Connect("inproc://listener"); //Print everything that arrives on pipe ZError error; ZFrame frame; while (true) { if (null == (frame = listener.ReceiveFrame(out error))) { if (error == ZError.ETERM) return; // Interrupted throw new ZException(error); } using (frame) frame.DumpZfrm(); } } }
public static void PSEnvPub(string[] args) { // // Pubsub envelope publisher // // Author: metadings // // Prepare our context and publisher using (var context = new ZContext()) using (var publisher = new ZSocket(context, ZSocketType.PUB)) { publisher.Linger = TimeSpan.Zero; publisher.Bind("tcp://*:5563"); while (true) { // Write two messages, each with an envelope and content using (var message = new ZMessage()) { message.Add(new ZFrame("A")); message.Add(new ZFrame("We don't want to see this")); publisher.Send(message); } using (var message = new ZMessage()) { message.Add(new ZFrame("B")); message.Add(new ZFrame("We would like to see this")); publisher.Send(message); } Thread.Sleep(1000); } } }
static void RTReq_Worker(int i) { using (var context = new ZContext()) using (var worker = new ZSocket(context, ZSocketType.REQ)) { worker.IdentityString = "PEER" + i; // Set a printable identity worker.Connect("tcp://127.0.0.1:5671"); int total = 0; while (true) { // Tell the broker we're ready for work worker.Send(new ZFrame("Hi Boss")); // Get workload from broker, until finished using (ZFrame frame = worker.ReceiveFrame()) { bool finished = (frame.ReadString() == "Fired!"); if (finished) { break; } } total++; // Do some random work Thread.Sleep(1); } Console.WriteLine("Completed: PEER{0}, {1} tasks", i, total); } }
public TaskWorker(string workerid="*",string SenderIP = "127.0.0.1", int SenderPort = 5557, string sinkIP = "127.0.0.1", int sinkPort=5558) { // // Task worker // Connects PULL socket to tcp://localhost:5557 // Collects workloads from ventilator via that socket // Connects PUSH socket to tcp://localhost:5558 // Sends results to sink via that socket // // Author: metadings // // Socket to receive messages on and // Socket to send messages to using (var context = new ZContext()) using (var receiver = new ZSocket(context, ZSocketType.PULL)) using (var sink = new ZSocket(context, ZSocketType.PUSH)) { receiver.Connect(String.Format ("tcp://{0}:{1}",SenderIP,SenderPort)); sink.Connect(string.Format("tcp://{0}:{1}",sinkIP,sinkPort )); Console.WriteLine("Worker " + workerid + " ready."); // Process tasks forever while (true) { var replyBytes = new byte[4]; receiver.ReceiveBytes(replyBytes, 0, replyBytes.Length); int workload = BitConverter.ToInt32(replyBytes, 0); Console.WriteLine("{0}.", workload); // Show progress Thread.Sleep(workload); // Do the work sink.Send(new byte[0], 0, 0); // Send results to sink } } }
unsafe internal static bool PollSingle( ZSocket socket, ZPollItem item, ZPoll pollEvents, out ZError error, TimeSpan? timeout = null) { error = default(ZError); bool result = false; int timeoutMs = !timeout.HasValue ? -1 : (int)timeout.Value.TotalMilliseconds; zmq_pollitem_posix_t* native = stackalloc zmq_pollitem_posix_t[1]; // fixed (zmq_pollitem_posix_t* native = managedArray) { native->SocketPtr = socket.SocketPtr; native->Events = (short)(item.Events & pollEvents); native->ReadyEvents = (short)ZPoll.None; while (!(result = (-1 != zmq.poll(native, 1, timeoutMs)))) { error = ZError.GetLastErr(); if (error == ZError.EINTR) { error = default(ZError); continue; } break; } item.ReadyEvents = (ZPoll)native->ReadyEvents; //} return result; }
public static void TaskWork(string[] args) { // // Task worker // Connects PULL socket to tcp://127.0.0.1:5557 // Collects workloads from ventilator via that socket // Connects PUSH socket to tcp://127.0.0.1:5558 // Sends results to sink via that socket // // Author: metadings // // Socket to receive messages on and // Socket to send messages to using (var context = new ZContext()) using (var receiver = new ZSocket(context, ZSocketType.PULL)) using (var sink = new ZSocket(context, ZSocketType.PUSH)) { receiver.Connect("tcp://127.0.0.1:5557"); sink.Connect("tcp://127.0.0.1:5558"); // Process tasks forever while (true) { var replyBytes = new byte[4]; receiver.ReceiveBytes(replyBytes, 0, replyBytes.Length); int workload = BitConverter.ToInt32(replyBytes, 0); Console.WriteLine("{0}.", workload); // Show progress Thread.Sleep(workload); // Do the work sink.Send(new byte[0], 0, 0); // Send results to sink } } }
private static void Handle(Header header, ZFrame bodyFrame) { //TODO - really we'd have a message handler factory: if (header.BodyType == typeof(SendFulfilmentCommand).Name) { var command = JsonConvert.DeserializeObject<SendFulfilmentCommand>(bodyFrame.ReadString()); var client = FulfilmentClientFactory.GetApiClient(command.FulfilmentType); try { client.Send(command.Address); Console.WriteLine("*** Sent fulfilment, type: {0}, to address: {1}", command.FulfilmentType, command.Address); } catch (Exception ex) { Console.WriteLine("*** Fulfilment failed, resending message"); var queueAddress = Config.Get("Queues.Fulfilment.Address"); header.HandledCount++; header.LastExceptionMessage = ex.Message; var messageFrames = new List<ZFrame>(); messageFrames.Add(new ZFrame(JsonConvert.SerializeObject(header))); messageFrames.Add(bodyFrame); using (var context = new ZContext()) using (var sender = new ZSocket(context, ZSocketType.PUSH)) { sender.Connect(queueAddress); sender.Send(new ZMessage(messageFrames)); } } } }
static void Main(string[] args) { var queueAddress = Config.Get("Queues.Fulfilment.Address"); using (var context = new ZContext()) using (var receiver = new ZSocket(context, ZSocketType.PULL)) { receiver.Bind(queueAddress); Console.WriteLine("Listening for messages on: " + queueAddress); while (true) { using (var message = receiver.ReceiveMessage()) { var headerFrame = message.First(); var header = JsonConvert.DeserializeObject<Header>(headerFrame.ReadString()); Console.WriteLine("* Received message, ID: {0}, body type: {1}, handled count: {2}", header.MessageId, header.BodyType, header.HandledCount); //assume this is a permanent failure if (header.HandledCount < 3) { Console.WriteLine("** Handling message. Previous attempts: {0}", header.HandledCount); Handle(header, message.ElementAt(1)); } else { Console.WriteLine("!! Message has failed {0} times. Not processing. Last exception: {1}", header.HandledCount, header.LastExceptionMessage); //TODO - forward to error queue } } Thread.Sleep(100); } } }
public static void RRClient(string[] args) { // // Hello World client // Connects REQ socket to tcp://localhost:5559 // Sends "Hello" to server, expects "World" back // // Author: metadings // // Socket to talk to server using (var context = new ZContext()) using (var requester = new ZSocket(context, ZSocketType.REQ)) { requester.Connect("tcp://127.0.0.1:5559"); for (int n = 0; n < 10; ++n) { requester.Send(new ZFrame("Hello")); using (ZFrame reply = requester.ReceiveFrame()) { Console.WriteLine("Hello {0}!", reply.ReadString()); } } } }
public static void Espresso(string[] args) { // // Espresso Pattern // This shows how to capture data using a pub-sub proxy // // Author: metadings // using (var context = new ZContext()) using (var subscriber = new ZSocket(context, ZSocketType.XSUB)) using (var publisher = new ZSocket(context, ZSocketType.XPUB)) using (var listener = new ZSocket(context, ZSocketType.PAIR)) { new Thread(() => Espresso_Publisher(context)).Start(); new Thread(() => Espresso_Subscriber(context)).Start(); new Thread(() => Espresso_Listener(context)).Start(); subscriber.Connect("tcp://127.0.0.1:6000"); publisher.Bind("tcp://*:6001"); listener.Bind("inproc://listener"); ZError error; if (!ZContext.Proxy(subscriber, publisher, listener, out error)) { if (error == ZError.ETERM) return; // Interrupted throw new ZException(error); } } }
// The subscriber thread requests messages starting with // A and B, then reads and counts incoming messages. static void Espresso0_Subscriber(ZContext context) { // Subscrie to "A" and "B" using (var subscriber = new ZSocket(context, ZSocketType.SUB)) { subscriber.Connect("tcp://127.0.0.1:6001"); subscriber.Subscribe("A"); subscriber.Subscribe("B"); ZError error; ZFrame frm; int count = 0; while (count < 5) { if (null == (frm = subscriber.ReceiveFrame(out error))) { if (error == ZError.ETERM) return; // Interrupted throw new ZException(error); } ++count; } Console.WriteLine("I: subscriber counted {0}", count); } }
static void Espresso_Subscriber(ZContext context) { // The subscriber thread requests messages starting with // A and B, then reads and counts incoming messages. using (var subscriber = new ZSocket(context, ZSocketType.SUB)) { subscriber.Connect("tcp://127.0.0.1:6001"); subscriber.Subscribe("A"); subscriber.Subscribe("B"); ZError error; ZFrame frame; int count = 0; while (count < 5) { if (null == (frame = subscriber.ReceiveFrame(out error))) { if (error == ZError.ETERM) return; // Interrupted throw new ZException(error); } ++count; } Console.WriteLine("I: subscriber counted {0}", count); } }
public static void Main(string[] args) { // // Multithreaded Hello World server // // Author: metadings // // Socket to talk to clients and // Socket to talk to workers using (var ctx = new ZContext()) using (var clients = new ZSocket(ctx, ZSocketType.ROUTER)) using (var workers = new ZSocket(ctx, ZSocketType.DEALER)) { clients.Bind("tcp://*:5555"); workers.Bind("inproc://workers"); // Launch pool of worker threads for (int i = 0; i < 5; ++i) { new Thread(() => MTServer_Worker(ctx)).Start(); } // Connect work threads to client threads via a queue proxy ZContext.Proxy(clients, workers); } }
static void Espresso_Publisher(ZContext context) { // The publisher sends random messages starting with A-J: using (var publisher = new ZSocket(context, ZSocketType.PUB)) { publisher.Bind("tcp://*:6000"); ZError error; while (true) { var bytes = new byte[5]; using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) { rng.GetBytes(bytes); } if (!publisher.SendBytes(bytes, 0, bytes.Length, ZSocketFlags.None, out error)) { if (error == ZError.ETERM) return; // Interrupted throw new ZException(error); } Thread.Sleep(1); } } }
static void Espresso_Subscriber(ZContext context) { // The subscriber thread requests messages starting with // A and B, then reads and counts incoming messages. using (var subscriber = new ZSocket(context, ZSocketType.SUB)) { subscriber.Connect("tcp://127.0.0.1:6001"); subscriber.Subscribe("A"); subscriber.Subscribe("B"); ZError error; int count = 0; while (count < 5) { var bytes = new byte[10]; int bytesLength; if (-1 == (bytesLength = subscriber.ReceiveBytes(bytes, 0, bytes.Length, ZSocketFlags.None, out error))) { if (error == ZError.ETERM) return; // Interrupted throw new ZException(error); } ++count; } Console.WriteLine("I: subscriber counted {0}", count); } }
public static void PSEnvSub(string[] args) { // // Pubsub envelope subscriber // // Author: metadings // // Prepare our context and subscriber using (var context = new ZContext()) using (var subscriber = new ZSocket(context, ZSocketType.SUB)) { subscriber.Connect("tcp://127.0.0.1:5563"); subscriber.Subscribe("B"); int subscribed = 0; while (true) { using (ZMessage message = subscriber.ReceiveMessage()) { subscribed++; // Read envelope with address string address = message[0].ReadString(); // Read message contents string contents = message[1].ReadString(); Console.WriteLine("{0}. [{1}] {2}", subscribed, address, contents); } } } }
// Basic request-reply client using REQ socket static void LBBroker_Client(ZContext context, int i) { // Create a socket using (var client = new ZSocket(context, ZSocketType.REQ)) { // Set a printable identity client.IdentityString = "CLIENT" + i; // Connect client.Connect("inproc://frontend"); using (var request = new ZMessage()) { request.Add(new ZFrame("Hello")); // Send request client.Send(request); } // Receive reply using (ZMessage reply = client.ReceiveMessage()) { Console.WriteLine("CLIENT{0}: {1}", i, reply[0].ReadString()); } } }
public FLClient() { // Constructor context = new ZContext(); socket = new ZSocket(context, ZSocketType.DEALER); socket.Linger = GLOBAL_TIMEOUT; }
/// <summary> /// Creation d'un Publisher /// Les valeurs par defaut sont _ip = "*", _port = 5555 /// </summary> /// <param name="_ip"></param> /// <param name="_port"></param> public Publisher(string _ip = "*", int _port = 5555) { // Initialisation Context = new ZContext(); Socket = new ZSocket(context, ZSocketType.PUB); // Bind this.BindSocket(_ip, _port); }
public void ConnectToBroker() { // Connect or reconnect to broker Client = new ZSocket(_context, ZSocketType.REQ); Client.Connect(Broker); if (Verbose) "I: connecting to broker at '{0}'...".DumpString(Broker); }
public override void Start() { base.Start(); if (Frontend == null) { Frontend = ZSocket.Create(Context, ZSocketType.PAIR); Frontend.Connect(Endpoint); } }
public static void MSReader(string[] args) { // // Reading from multiple sockets // This version uses a simple recv loop // // Author: metadings // using (var context = new ZContext()) using (var receiver = new ZSocket(context, ZSocketType.PULL)) using (var subscriber = new ZSocket(context, ZSocketType.SUB)) { // Connect to task ventilator receiver.Connect("tcp://127.0.0.1:5557"); // Connect to weather server subscriber.Connect("tcp://127.0.0.1:5556"); subscriber.SetOption(ZSocketOption.SUBSCRIBE, "10001 "); // Process messages from both sockets // We prioritize traffic from the task ventilator ZError error; ZFrame frame; while (true) { if (null != (frame = receiver.ReceiveFrame(ZSocketFlags.DontWait, out error))) { // Process task } else { if (error == ZError.ETERM) return; // Interrupted if (error != ZError.EAGAIN) throw new ZException(error); } if (null != (frame = subscriber.ReceiveFrame(ZSocketFlags.DontWait, out error))) { // Process weather update } else { if (error == ZError.ETERM) return; // Interrupted if (error != ZError.EAGAIN) throw new ZException(error); } // No activity, so sleep for 1 msec Thread.Sleep(1); } } }
static void LBBroker_Worker(ZContext context, int i) { // This is the worker task, using a REQ socket to do load-balancing. // Create socket using (var worker = new ZSocket(context, ZSocketType.REQ)) { // Set a printable identity worker.IdentityString = "WORKER" + i; // Connect worker.Connect("inproc://backend"); // Tell broker we're ready for work using (var ready = new ZFrame("READY")) { worker.Send(ready); } ZError error; ZMessage request; while (true) { // Get request if (null == (request = worker.ReceiveMessage(out error))) { // We are using "out error", // to NOT throw a ZException ETERM if (error == ZError.ETERM) break; throw new ZException(error); } using (request) { string worker_id = request[0].ReadString(); string requestText = request[2].ReadString(); Console.WriteLine("WORKER{0}: {1}", i, requestText); // Send reply using (var commit = new ZMessage()) { commit.Add(new ZFrame(worker_id)); commit.Add(new ZFrame()); commit.Add(new ZFrame("OK")); worker.Send(commit); } } } } }
public static void RRBroker(string[] args) { // // Simple request-reply broker // // Author: metadings // // Prepare our context and sockets using (var ctx = new ZContext()) using (var frontend = new ZSocket(ctx, ZSocketType.ROUTER)) using (var backend = new ZSocket(ctx, ZSocketType.DEALER)) { frontend.Bind("tcp://*:5559"); backend.Bind("tcp://*:5560"); // Initialize poll set var poll = ZPollItem.CreateReceiver(); // Switch messages between sockets ZError error; ZMessage message; while (true) { if (frontend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64))) { // Process all parts of the message Console_WriteZMessage("frontend", 2, message); backend.Send(message); } else { if (error == ZError.ETERM) return; // Interrupted if (error != ZError.EAGAIN) throw new ZException(error); } if (backend.PollIn(poll, out message, out error, TimeSpan.FromMilliseconds(64))) { // Process all parts of the message Console_WriteZMessage(" backend", 2, message); frontend.Send(message); } else { if (error == ZError.ETERM) return; // Interrupted if (error != ZError.EAGAIN) throw new ZException(error); } } } }
static void MTRelay_step1(ZContext ctx) { // Connect to step2 and tell it we're ready using (var xmitter = new ZSocket(ctx, ZSocketType.PAIR)) { xmitter.Connect("inproc://step2"); Console.WriteLine("Step 1 ready, signaling step 2"); xmitter.Send(new ZFrame("READY")); } }
public static void RTReq(string[] args) { // // ROUTER-to-REQ example // // While this example runs in a single process, that is only to make // it easier to start and stop the example. Each thread has its own // context and conceptually acts as a separate process. // // Author: metadings // using (var context = new ZContext()) using (var broker = new ZSocket(context, ZSocketType.ROUTER)) { broker.Bind("tcp://*:5671"); for (int i = 0; i < RTReq_Workers; ++i) { int j = i; new Thread(() => RTReq_Worker(j)).Start(); } var stopwatch = new Stopwatch(); stopwatch.Start(); // Run for five seconds and then tell workers to end int workers_fired = 0; while (true) { // Next message gives us least recently used worker using (ZMessage identity = broker.ReceiveMessage()) { broker.SendMore(identity[0]); broker.SendMore(new ZFrame()); // Encourage workers until it's time to fire them if (stopwatch.Elapsed < TimeSpan.FromSeconds(5)) { broker.Send(new ZFrame("Work harder!")); } else { broker.Send(new ZFrame("Fired!")); if (++workers_fired == RTReq_Workers) { break; } } } } } }
public static void RRWorker(string[] args) { // // Hello World worker // Connects REP socket to tcp://127.0.0.1:5560 // Expects "Hello" from client, replies with "World" // // Author: metadings // if (args == null || args.Length < 2) { Console.WriteLine(); Console.WriteLine("Usage: ./{0} RRWorker [Name] [Endpoint]", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(); Console.WriteLine(" Name Your Name"); Console.WriteLine(" Endpoint Where RRWorker should connect to."); Console.WriteLine(" Default is tcp://127.0.0.1:5560"); Console.WriteLine(); if (args.Length < 1) { args = new string[] { "World", "tcp://127.0.0.1:5560" }; } else { args = new string[] { args[0], "tcp://127.0.0.1:5560" }; } } string name = args[0]; string endpoint = args[1]; // Socket to talk to clients using (var context = new ZContext()) using (var responder = new ZSocket(context, ZSocketType.REP)) { responder.Connect(endpoint); while (true) { // Wait for next request from client using (ZFrame request = responder.ReceiveFrame()) { Console.Write("{0} ", request.ReadString()); // Do some 'work' Thread.Sleep(1); // Send reply back to client Console.WriteLine("{0}... ", name); responder.Send(new ZFrame(name)); } } } }
public static void MSPoller(string[] args) { // // Reading from multiple sockets // This version uses zmq_poll() // // Author: metadings // using (var context = new ZContext()) using (var receiver = new ZSocket(context, ZSocketType.PULL)) using (var subscriber = new ZSocket(context, ZSocketType.SUB)) { // Connect to task ventilator receiver.Connect("tcp://127.0.0.1:5557"); // Connect to weather server subscriber.Connect("tcp://127.0.0.1:5556"); subscriber.SetOption(ZSocketOption.SUBSCRIBE, "10001 "); var poll = ZPollItem.CreateReceiver(); // Process messages from both sockets ZError error; ZMessage msg; while (true) { if (receiver.PollIn(poll, out msg, out error, TimeSpan.FromMilliseconds(64))) { // Process task } else { if (error == ZError.ETERM) return; // Interrupted if (error != ZError.EAGAIN) throw new ZException(error); } if (subscriber.PollIn(poll, out msg, out error, TimeSpan.FromMilliseconds(64))) { // Process weather update } else { if (error == ZError.ETERM) return; // Interrupted if (error != ZError.EAGAIN) throw new ZException(error); } } } }
public void ConnectToBroker() { // Connect or reconnect to broker. In this asynchronous class we use a // DEALER socket instead of a REQ socket; this lets us send any number // of requests without waiting for a reply. Client = new ZSocket(_context, ZSocketType.DEALER); Client.Connect(Broker); if (Verbose) "I: connecting to broker at '{0}'...".DumpString(Broker); }
public static void PathoPub(string[] args) { // // Pathological publisher // Sends out 1,000 topics and then one random update per second // // Author: metadings // if (args == null || args.Length < 1) { Console.WriteLine(); Console.WriteLine("Usage: ./{0} PathoPub [Endpoint]", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(); Console.WriteLine(" Endpoint Where PathoPub should connect to."); Console.WriteLine(" Default is null, Binding on tcp://*:5556"); Console.WriteLine(); args = new string[] { null }; } using (var context = new ZContext()) using (var publisher = new ZSocket(context, ZSocketType.PUB)) { if (args[0] != null) { publisher.Connect(args[0]); } else { publisher.Bind("tcp://*:5556"); } // Ensure subscriber connection has time to complete Thread.Sleep(100); // Send out all 1,000 topic messages for (int topic = 0; topic < 1000; ++topic) { publisher.SendMore(new ZFrame(string.Format("{0:D3}", topic))); publisher.Send(new ZFrame("Save Roger")); } // Send one random update per second var rnd = new Random(); while (true) { Thread.Sleep(10); publisher.SendMore(new ZFrame(string.Format("{0:D3}", rnd.Next(1000)))); publisher.Send(new ZFrame("Off with his head!")); } } }
// // Broker peering simulation (part 1) // Prototypes the state flow // // Author: metadings // public static void Peering1(IDictionary <string, string> dict, string[] args) { // First argument is this broker's name // Other arguments are our peers' names // if (args == null || args.Length < 2) { Console.WriteLine(); Console.WriteLine("Usage: {0} Peering1 World Receiver0", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(" {0} Peering1 Receiver0 World", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(); return; } string self = args[0]; Console.WriteLine("I: preparing broker as {0}", self); using (var context = new ZContext()) using (var backend = new ZSocket(context, ZSocketType.PUB)) using (var frontend = new ZSocket(context, ZSocketType.SUB)) { // Bind backend to endpoint backend.Bind("tcp://127.0.0.1:" + Peering1_GetPort(self)); // Connect frontend to all peers frontend.SubscribeAll(); for (int i = 1; i < args.Length; ++i) { string peer = args[i]; Console.WriteLine("I: connecting to state backend at {0}", peer); frontend.Connect("tcp://127.0.0.1:" + Peering1_GetPort(peer)); } // The main loop sends out status messages to peers, and collects // status messages back from peers. The zmq_poll timeout defines // our own heartbeat: ZError error; ZMessage incoming; var poll = ZPollItem.CreateReceiver(); var rnd = new Random(); while (true) { // Poll for activity, or 1 second timeout if (!frontend.PollIn(poll, out incoming, out error, TimeSpan.FromSeconds(1))) { if (error == ZError.EAGAIN) { error = ZError.None; using (var output = new ZMessage()) { output.Add(new ZFrame(self)); var outputNumber = ZFrame.Create(4); outputNumber.Write(rnd.Next(10)); output.Add(outputNumber); backend.Send(output); } continue; } if (error == ZError.ETERM) { return; } throw new ZException(error); } using (incoming) { string peer_name = incoming[0].ReadString(); int available = incoming[1].ReadInt32(); Console.WriteLine("{0} - {1} workers free", peer_name, available); } } } }
public static void FLServer3(IDictionary <string, string> dict, string[] args) { // // Freelance server - Model 3 // Uses an ROUTER/ROUTER socket but just one thread // // Author: metadings // // Prepare server socket with predictable identity string bind_endpoint = "tcp://*:5555"; string connect_endpoint = "tcp://127.0.0.1:5555"; using (var context = ZContext.Create()) using (var server = ZSocket.Create(context, ZSocketType.ROUTER)) { Console.CancelKeyPress += (s, ea) => { ea.Cancel = true; context.Shutdown(); }; server.IdentityString = connect_endpoint; server.Bind(bind_endpoint); Console.WriteLine("I: service is ready as {0}", bind_endpoint); ZError error; ZMessage request; while (true) { if (null == (request = server.ReceiveMessage(out error))) { if (error == ZError.ETERM) { break; // Interrupted } throw new ZException(error); } using (var response = new ZMessage()) { ZFrame identity; using (request) { Console_WriteZMessage(request, "Receiving"); // Frame 0: identity of client // Frame 1: PING, or client control frame // Frame 2: request body identity = request.Pop(); ZFrame control = request.Pop(); string controlMessage = control.ReadString(); if (controlMessage == "PING") { control.Dispose(); response.Add(new ZFrame("PONG")); } else { response.Add(control); response.Add(new ZFrame("OK")); } } response.Prepend(identity); Console_WriteZMessage(response, "Sending "); if (!server.Send(response, out error)) { if (error == ZError.ETERM) { break; // Interrupted } throw new ZException(error); } } } if (error == ZError.ETERM) { Console.WriteLine("W: interrupted"); } } }
public static void Broker(ZContext context, string brokerAddrRequest, string brokerAddrResponse, string brokerAddrRequestPush, string brokerAddrResponsePull, string brokerAddrRequestPub, string brokerAddrResponseSub, string AddrToBroker1, string AddrToBroker2, string AddrFromBrokers, string brokerIdentity) { List <ArrayList> requestEndpoints = new List <ArrayList>(); List <ArrayList> responseEndpoints = new List <ArrayList>(); List <ArrayList> copies = new List <ArrayList>(); using (var brokerRequest = new ZSocket(context, ZSocketType.ROUTER)) using (var brokerResponse = new ZSocket(context, ZSocketType.DEALER)) using (var brokerRequestPush = new ZSocket(context, ZSocketType.PULL)) using (var brokerResponsePull = new ZSocket(context, ZSocketType.PUSH)) using (var brokerRequestPub = new ZSocket(context, ZSocketType.SUB)) using (var brokerResponseSub = new ZSocket(context, ZSocketType.PUB)) using (var brokerToOtherBroker1 = new ZSocket(context, ZSocketType.DEALER)) using (var brokerToOtherBroker2 = new ZSocket(context, ZSocketType.DEALER)) using (var brokerFromBrokers = new ZSocket(context, ZSocketType.DEALER)) { brokerRequestPub.SubscribeAll(); String reqMonitorAddr = "inproc://req." + brokerIdentity; brokerRequest.Monitor(reqMonitorAddr); ZMonitor reqMonitor = ZMonitor.Create(context, reqMonitorAddr); reqMonitor.Start(); bool reqConnected = false; bool reqDisconnected = false; reqMonitor.Disconnected += (s, a) => { reqDisconnected = true; reqConnected = false; }; reqMonitor.Accepted += (s, a) => { reqConnected = true; reqDisconnected = false; }; String subMonitorAddr = "inproc://sub." + brokerIdentity; brokerResponseSub.Monitor(subMonitorAddr); ZMonitor subMonitor = ZMonitor.Create(context, subMonitorAddr); subMonitor.Start(); bool subConnected = false; bool subDisconnected = false; subMonitor.Disconnected += (s, a) => { subDisconnected = true; subConnected = false; }; subMonitor.Accepted += (s, a) => { subConnected = true; }; String pullMonitorAddr = "inproc://pull." + brokerIdentity; brokerResponsePull.Monitor(pullMonitorAddr); ZMonitor pullMonitor = ZMonitor.Create(context, pullMonitorAddr); pullMonitor.Start(); bool pullConnected = false; bool pullDisconnected = false; pullMonitor.Disconnected += (s, a) => { pullDisconnected = true; pullConnected = false; }; pullMonitor.Accepted += (s, a) => { pullConnected = true; }; brokerRequest.Bind(brokerAddrRequest); brokerResponse.Bind(brokerAddrResponse); brokerFromBrokers.Bind(AddrFromBrokers); brokerToOtherBroker1.Connect(AddrToBroker1); brokerToOtherBroker2.Connect(AddrToBroker2); brokerRequestPush.Bind(brokerAddrRequestPush); brokerResponsePull.Bind(brokerAddrResponsePull); brokerRequestPub.Bind(brokerAddrRequestPub); brokerResponseSub.Bind(brokerAddrResponseSub); ZError error; ZMessage request; ZPollItem poll = ZPollItem.CreateReceiver(); string fileRequest = "Request.txt"; string fileResponse = "Response.txt"; //string pathReq =".\\Request\\" + uid + ".txt"; //string pathRep = ".\\Request\\" + uid + ".txt"; Directory.CreateDirectory("Request"); Directory.CreateDirectory("Response"); if (!File.Exists(fileRequest)) { File.Create(fileRequest).Close(); } if (!File.Exists(fileResponse)) { File.Create(fileResponse).Close(); } while (true) { SendCopies(copies, brokerIdentity); if (requestEndpoints.Any()) { for (int i = 0; i < requestEndpoints.Count; i++) { string content = requestEndpoints[i][0].ToString(); string uid = requestEndpoints[i][1].ToString(); if (requestEndpoints[i].Count > 5) { string addrOrTopic; if (requestEndpoints[i][5].ToString().Length == 20) { addrOrTopic = requestEndpoints[i][5].ToString().Substring(16, 4); } else { addrOrTopic = requestEndpoints[i][5].ToString(); } ZSocket socket = (ZSocket)requestEndpoints[i][3]; string address = socket.LastEndpoint.Substring(14, 4); bool sended = false; if (addrOrTopic == address) { if (socket.SocketType == ZSocketType.PUSH & pullDisconnected == false & pullConnected == true) { sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server"); } else { sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server"); } } else if (socket.SocketType == ZSocketType.PUB & subDisconnected == false & subConnected == true) { sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server", addrOrTopic); } if (socket != brokerResponse && sended == true) { RemoveFromList(requestEndpoints, Guid.Parse(uid)); string messageType = "REP"; MoveFile(uid, content); //WriteToFile(fileResponse, Guid.Parse(uid)); DeleteFile(uid); UpdateFile(fileRequest, uid); AddToList(copies, content, Guid.Parse(uid), messageType, null, null, brokerToOtherBroker1, brokerToOtherBroker2); } } } } if (responseEndpoints.Any()) { for (int i = 0; i < responseEndpoints.Count; i++) { string content = responseEndpoints[i][0].ToString(); string uid = responseEndpoints[i][1].ToString(); if (responseEndpoints[i].Count > 4) { string identity = responseEndpoints[i][2].ToString(); ZSocket socket = (ZSocket)responseEndpoints[i][3]; string address = responseEndpoints[i][4].ToString().Substring(14, 4); string address2 = brokerRequest.LastEndpoint.Substring(14, 4); if (address == address2) { if (reqDisconnected == true & reqConnected == false) { Thread.Sleep(5 * 1000); } if (reqDisconnected == false & reqConnected == true) { Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, identity); DeleteFile(uid); UpdateFile(fileResponse, uid); RemoveFromList(responseEndpoints, Guid.Parse(uid)); string messageType = "CON"; AddToList(copies, content, Guid.Parse(uid), messageType, null, null, brokerToOtherBroker1, brokerToOtherBroker2); } } } } } if (brokerRequest.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string receiverAddress = request[2].ReadString(); string identity = request[3].ReadString(); string content = request[4].ReadString(); string messageType = "REQ"; string senderAddress = brokerRequest.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1); Guid guid = Guid.NewGuid(); Console.WriteLine("{0} <- {1} : [{2} {3}]", brokerIdentity, identity, messageType, guid.ToString()); CreateFile(guid, content); WriteToFile(fileRequest, guid); AddToList(requestEndpoints, content, guid, identity, senderAddress, receiverAddress, brokerResponse); AddToList(copies, content, guid, messageType, senderAddress, receiverAddress, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } if (brokerRequestPush.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string receiverAddress = request[0].ReadString(); string identity = request[1].ReadString(); string content = request[2].ReadString(); string messageType = "REQ"; string senderAddress = brokerRequestPush.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1); Guid guid = Guid.NewGuid(); Console.WriteLine("{0} <- {1} : [{2}]", brokerIdentity, identity, guid.ToString()); CreateFile(guid, content); WriteToFile(fileRequest, guid); AddToList(requestEndpoints, content, guid, identity, senderAddress, receiverAddress, brokerResponsePull); AddToList(copies, content, guid, messageType, senderAddress, receiverAddress, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } if (brokerRequestPub.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string topic = request[0].ReadString(); string identity = request[1].ReadString(); string content = request[2].ReadString(); string messageType = "REQ"; string senderAddress = brokerRequestPub.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1); Guid guid = Guid.NewGuid(); Console.WriteLine("{0} <- {1} : [{2}]", brokerIdentity, identity, guid.ToString()); CreateFile(guid, content, topic); WriteToFile(fileRequest, guid); AddToList(requestEndpoints, content, guid, identity, senderAddress, topic, brokerResponseSub); AddToList(copies, content, guid, messageType, senderAddress, topic, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } int counter = 1; do { if (brokerFromBrokers.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(100))) { string identity = request[0].ReadString(); string content = request[1].ReadString(); string uid = request[2].ReadString(); string messageType = request[3].ReadString(); string senderAddress = null; string receiverAddress = null; if (request.Count > 5) { senderAddress = request[4].ReadString(); receiverAddress = request[5].ReadString(); } else if (request.Count > 4) { senderAddress = request[4].ReadString(); } ZSocket socket2 = null; ZSocket socket = null; if ((brokerIdentity == "Broker1" & identity == "Broker2") || (brokerIdentity == "Broker2" & identity == "Broker1") || (brokerIdentity == "Broker3" & identity == "Broker1")) { socket = brokerToOtherBroker1; } else if ((brokerIdentity == "Broker1" & identity == "Broker3") || (brokerIdentity == "Broker2" & identity == "Broker3") || (brokerIdentity == "Broker3" & identity == "Broker2")) { socket = brokerToOtherBroker2; } if (messageType == "CONCOP") { RemoveFromList(copies, Guid.Parse(uid), content, socket); } else { if (messageType == "REQ") { if (AddressforClientReq.Contains(senderAddress)) { socket2 = brokerResponse; } else if (AddressforClientPush.Contains(senderAddress)) { socket2 = brokerResponsePull; } else if (AddressforClientPub.Contains(senderAddress)) { socket2 = brokerResponseSub; } AddToList(requestEndpoints, content, Guid.Parse(uid), identity, senderAddress, receiverAddress, socket2); } else if (messageType == "REP") { if (AddressforClientReq.Contains(senderAddress)) { var list = GetFromList(requestEndpoints, Guid.Parse(uid)); if (list != null) { string identity2 = list[2].ToString(); AddToList(responseEndpoints, content, Guid.Parse(uid), identity2, senderAddress, null, brokerRequest); } } RemoveFromList(requestEndpoints, Guid.Parse(uid)); } else if (messageType == "CON") { RemoveFromList(responseEndpoints, Guid.Parse(uid)); } Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), messageType, uid, "CONCOP", null, null); } } else { ErrorChecker(error); } counter++; }while (copies.Any() & counter < 4); if (brokerResponse.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string uid = request[2].ReadString(); string identity = request[3].ReadString(); string content = request[4].ReadString(); string messageType = "REP"; ArrayList list = GetFromList(requestEndpoints, Guid.Parse(uid)); string address = list[4].ToString(); string identity2 = list[2].ToString(); Console.WriteLine("{0} <- {1} : [{2} {3}]", brokerIdentity, identity, uid, messageType); MoveFile(uid, content); WriteToFile(fileResponse, Guid.Parse(uid)); UpdateFile(fileRequest, uid); RemoveFromList(requestEndpoints, Guid.Parse(uid)); AddToList(responseEndpoints, content, Guid.Parse(uid), identity2, address, null, brokerRequest); AddToList(copies, content, Guid.Parse(uid), messageType, address, null, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } } } }
public static void LPClient(IDictionary <string, string> dict, string[] args) { if (args == null || args.Length < 1) { Console.WriteLine(); Console.WriteLine("Usage: ./{0} LPClient [Name]", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(); Console.WriteLine(" Name Your name. Default: People"); Console.WriteLine(); args = new string[] { "People" }; } string name = args[0]; ZSocket requester = null; try { // using (requester) using (var context = new ZContext()) { ZError error; if (null == (requester = LPClient_CreateZSocket(context, name, out error))) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } int sequence = 0; int retries_left = LPClient_RequestRetries; var poll = ZPollItem.CreateReceiver(); while (retries_left > 0) { // We send a request, then we work to get a reply using (var outgoing = ZFrame.Create(4)) { outgoing.Write(++sequence); requester.Send(outgoing); } ZMessage incoming; while (true) { // Here we process a server reply and exit our loop // if the reply is valid. // If we didn't a reply, we close the client socket // and resend the request. We try a number of times // before finally abandoning: // Poll socket for a reply, with timeout if (requester.PollIn(poll, out incoming, out error, LPClient_RequestTimeout)) { using (incoming) { // We got a reply from the server int incoming_sequence = incoming[0].ReadInt32(); if (sequence == incoming_sequence) { Console.WriteLine("I: server replied OK ({0})", incoming_sequence); retries_left = LPClient_RequestRetries; break; } else { Console_WriteZMessage(incoming, "E: malformed reply from server"); } } } else { if (error == ZError.EAGAIN) { if (--retries_left == 0) { Console.WriteLine("E: server seems to be offline, abandoning"); break; } Console.WriteLine("W: no response from server, retrying..."); // Old socket is confused; close it and open a new one requester.Dispose(); if (null == (requester = LPClient_CreateZSocket(context, name, out error))) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } Console.WriteLine("I: reconnected"); // Send request again, on new socket using (var outgoing = ZFrame.Create(4)) { outgoing.Write(sequence); requester.Send(outgoing); } continue; } if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } } } } finally { if (requester != null) { requester.Dispose(); requester = null; } } }
public MessageReceiver(string routingKey) { _queue = MessageMiddleware.Instace.CreateConsumer(routingKey); AddRoutingKey(routingKey); }
public MessageReceiver() { _queue = MessageMiddleware.Instace.CreateConsumer(); _processes = new ProcessTable(); }
public static void LVCache(IDictionary <string, string> dict, string[] args) { // // Last value cache // Uses XPUB subscription messages to re-send data // // Author: metadings // using (var context = new ZContext()) using (var frontend = new ZSocket(context, ZSocketType.SUB)) using (var backend = new ZSocket(context, ZSocketType.XPUB)) { // Subscribe to every single topic from publisher frontend.Bind("tcp://*:5557"); frontend.SubscribeAll(); backend.Bind("tcp://*:5558"); // Store last instance of each topic in a cache var cache = new HashSet <LVCacheItem>(); // We route topic updates from frontend to backend, and // we handle subscriptions by sending whatever we cached, // if anything: var p = ZPollItem.CreateReceiver(); ZMessage msg; ZError error; while (true) { // Any new topic data we cache and then forward if (frontend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1))) { using (msg) { string topic = msg[0].ReadString(); string current = msg[1].ReadString(); LVCacheItem previous = cache.FirstOrDefault(item => topic == item.Topic); if (previous != null) { cache.Remove(previous); } cache.Add(new LVCacheItem { Topic = topic, Current = current }); backend.Send(msg); } } else { if (error == ZError.ETERM) { break; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } } // When we get a new subscription, we pull data from the cache: if (backend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1))) { using (msg) { // Event is one byte 0=unsub or 1=sub, followed by topic byte subscribe = msg[0].ReadAsByte(); if (subscribe == 0x01) { string topic = msg[0].ReadString(); LVCacheItem previous = cache.FirstOrDefault(item => topic == item.Topic); if (previous != null) { Console.WriteLine("Sending cached topic {0}", topic); backend.SendMore(new ZFrame(previous.Topic)); backend.Send(new ZFrame(previous.Current)); } else { Console.WriteLine("Failed to send cached topic {0}!", topic); } } } } else { if (error == ZError.ETERM) { break; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } } } } }
public static void Agent(ZContext context, ZSocket backend, CancellationTokenSource cancellor, object[] args) { // Finally, here's the agent task itself, which polls its two sockets // and processes incoming messages: using (var agent = new Agent(context, backend)) { var p = ZPollItem.CreateReceiver(); while (!cancellor.IsCancellationRequested) { ZMessage msg; ZError error; // Poll the control message if (agent.Pipe.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(64))) { using (msg) { agent.ControlMessage(msg); } } else { if (error == ZError.ETERM) { break; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } } // Poll the router message if (agent.Router.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(64))) { using (msg) { agent.RouterMessage(msg); } } else { if (error == ZError.ETERM) { break; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } } if (agent.Request != null) { // If we're processing a request, dispatch to next server if (DateTime.UtcNow >= agent.Expires) { // Request expired, kill it using (var outgoing = new ZFrame("FAILED")) { agent.Pipe.Send(outgoing); } agent.Request.Dispose(); agent.Request = null; } else { // Find server to talk to, remove any expired ones foreach (Server server in agent.Actives.ToList()) { if (DateTime.UtcNow >= server.Expires) { agent.Actives.Remove(server); server.Alive = false; } else { // Copy the Request, Push the Endpoint and send on Router using (var request = agent.Request.Duplicate()) { request.Prepend(new ZFrame(server.Endpoint)); agent.Router.Send(request); break; } } } } } // Disconnect and delete any expired servers // Send heartbeats to idle servers if needed foreach (Server server in agent.Servers) { server.Ping(agent.Router); } } } }
private void StartListeners() { var serializer = new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var knownPools = new HashSet <string>(clusterConfig.Pools.Select(x => x.Id)); foreach (var relay in clusterConfig.ShareRelays) { Task.Run(() => { var url = relay.Url; // Receive loop var done = false; while (!done) { try { using (var subSocket = new ZSocket(ZSocketType.SUB)) { subSocket.SetupCurveTlsClient(relay.SharedEncryptionKey, logger); subSocket.ReceiveTimeout = relayReceiveTimeout; subSocket.Connect(url); subSocket.SubscribeAll(); if (subSocket.CurveServerKey != null) { logger.Info($"Monitoring external stratum {url} using Curve public-key {subSocket.CurveServerKey.ToHexString()}"); } else { logger.Info($"Monitoring external stratum {url}"); } while (true) { string topic; uint flags; byte[] data; // receive using (var msg = subSocket.ReceiveMessage()) { // extract frames topic = msg[0].ToString(Encoding.UTF8); flags = msg[1].ReadUInt32(); data = msg[2].Read(); } // validate if (string.IsNullOrEmpty(topic) || !knownPools.Contains(topic)) { logger.Warn(() => $"Received share for pool '{topic}' which is not known locally. Ignoring ..."); continue; } if (data?.Length == 0) { logger.Warn(() => $"Received empty data from {url}/{topic}. Ignoring ..."); continue; } // TMP FIX if ((flags & ShareRelay.WireFormatMask) == 0) { flags = BitConverter.ToUInt32(BitConverter.GetBytes(flags).ToNewReverseArray()); } // deserialize var wireFormat = (ShareRelay.WireFormat)(flags & ShareRelay.WireFormatMask); Share share = null; switch (wireFormat) { case ShareRelay.WireFormat.Json: using (var stream = new MemoryStream(data)) { using (var reader = new StreamReader(stream, Encoding.UTF8)) { using (var jreader = new JsonTextReader(reader)) { share = serializer.Deserialize <Share>(jreader); } } } break; case ShareRelay.WireFormat.ProtocolBuffers: using (var stream = new MemoryStream(data)) { share = Serializer.Deserialize <Share>(stream); share.BlockReward = (decimal)share.BlockRewardDouble; } break; default: logger.Error(() => $"Unsupported wire format {wireFormat} of share received from {url}/{topic} "); break; } if (share == null) { logger.Error(() => $"Unable to deserialize share received from {url}/{topic}"); continue; } // store share.PoolId = topic; share.Created = clock.Now; messageBus.SendMessage(new ClientShare(null, share)); // update poolstats from shares if (pools.TryGetValue(topic, out var poolContext)) { var pool = poolContext.Pool; poolContext.Logger.Info(() => $"External {(!string.IsNullOrEmpty(share.Source) ? $"[{share.Source.ToUpper()}] " : string.Empty)}share accepted: D={Math.Round(share.Difficulty, 3)}"); if (pool.NetworkStats != null) { pool.NetworkStats.BlockHeight = (ulong)share.BlockHeight; pool.NetworkStats.NetworkDifficulty = share.NetworkDifficulty; if (poolContext.BlockHeight != share.BlockHeight) { pool.NetworkStats.LastNetworkBlockTime = clock.Now; poolContext.BlockHeight = share.BlockHeight; poolContext.LastBlock = clock.Now; } else { pool.NetworkStats.LastNetworkBlockTime = poolContext.LastBlock; } } } else { logger.Info(() => $"External {(!string.IsNullOrEmpty(share.Source) ? $"[{share.Source.ToUpper()}] " : string.Empty)}share accepted: D={Math.Round(share.Difficulty, 3)}"); } } } } catch (ObjectDisposedException) { logger.Info($"Exiting monitoring thread for external stratum {url}]"); break; } catch (Exception ex) { logger.Error(ex); } } }); } if (clusterConfig.ShareRelays.Any()) { logger.Info(() => "Online"); } }
public static void RemoveFromList(List <ArrayList> ReqResList, Guid uid, string messageType = null, ZSocket socket = null) { if (messageType != null) { ReqResList.RemoveAll(x => Guid.Parse(x[1].ToString()) == uid & x[2].ToString() == messageType & x[3] == socket); } else { ReqResList.RemoveAll(x => Guid.Parse(x[1].ToString()) == uid); } }
public Handler(IMediator mediator, ZSocket zSocket) { _mediator = mediator; _zSocket = zSocket; }
public static void AddToList(List <ArrayList> ReqResCopList, string content, Guid uid, string messageTypeOrIdentity, string senderAddr, string receiverAddr, ZSocket socket, ZSocket socket2 = null) { ArrayList list = new ArrayList(); list.Add(content); list.Add(uid); list.Add(messageTypeOrIdentity); list.Add(socket); if (senderAddr != null) { list.Add(senderAddr); } if (receiverAddr != null) { list.Add(receiverAddr); } if (!ReqResCopList.Contains(list)) { ReqResCopList.Add(list); } if (socket2 != null) { ArrayList list2 = new ArrayList(); list2.Add(content); list2.Add(uid); list2.Add(messageTypeOrIdentity); list2.Add(socket2); if (senderAddr != null) { list2.Add(senderAddr); } if (receiverAddr != null) { list2.Add(receiverAddr); } if (!ReqResCopList.Contains(list2)) { ReqResCopList.Add(list2); } } }
public MessageReceiver(ICollection <string> routingKeys) { _queue = MessageMiddleware.Instace.CreateConsumer(routingKeys); AddRoutingKeys(routingKeys); }
/// <summary> /// 接收文本 /// </summary> /// <param name="socket"></param> /// <returns></returns> private ZeroResultData ReceiveString(ZSocket socket) { if (!ZeroApplication.ZerCenterIsRun) { return new ZeroResultData { State = ZeroOperatorStateType.LocalRecvError, InteractiveSuccess = false } } ; if (!socket.Recv(out var messages)) { if (!Equals(socket.LastError, ZError.EAGAIN)) { ZeroTrace.WriteError("Receive", socket.Connects.LinkToString(','), socket.LastError.Text, $"Socket Ptr:{socket.SocketPtr}"); } return(new ZeroResultData { State = ZeroOperatorStateType.LocalRecvError //ZmqErrorMessage = error?.Text, //ZmqErrorCode = error?.Number ?? 0 }); } try { var description = messages[0].Read(); if (description.Length == 0) { ZeroTrace.WriteError("Receive", "LaoutError", socket.Connects.LinkToString(','), description.LinkToString(p => p.ToString("X2"), ""), $"Socket Ptr:{socket.SocketPtr}."); return(new ZeroResultData { State = ZeroOperatorStateType.FrameInvalid, Message = "网络格式错误" }); } var end = description[0] + 1; if (end != messages.Count) { ZeroTrace.WriteError("Receive", "LaoutError", socket.Connects.LinkToString(','), $"FrameSize{messages.Count}", description.LinkToString(p => p.ToString("X2"), ""), $"Socket Ptr:{socket.SocketPtr}."); return(new ZeroResultData { State = ZeroOperatorStateType.FrameInvalid, Message = "网络格式错误" }); } var result = new ZeroResultData { InteractiveSuccess = true, State = (ZeroOperatorStateType)description[1] }; for (var idx = 1; idx < end; idx++) { result.Add(description[idx + 1], Encoding.UTF8.GetString(messages[idx].Read())); } return(result); } catch (Exception e) { ZeroTrace.WriteException("Receive", e, socket.Connects.LinkToString(','), $"Socket Ptr:{socket.SocketPtr}."); return(new ZeroResultData { State = ZeroOperatorStateType.LocalException, Exception = e }); } finally { messages.Dispose(); } }
public static void PPWorker(IDictionary <string, string> dict, string[] args) { if (args == null || args.Length == 0) { args = new string[] { "World" }; } string name = args[0]; ZError error; using (var context = ZContext.Create()) { ZSocket worker = null; try // using (worker) { if (null == (worker = PPWorker_CreateZSocket(context, name, out error))) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } // If liveness hits zero, queue is considered disconnected int liveness = Worker.PPP_HEARTBEAT_LIVENESS; int interval = Worker.PPP_INTERVAL_INIT; // Send out heartbeats at regular intervals DateTime heartbeat_at = DateTime.UtcNow + Worker.PPP_HEARTBEAT_INTERVAL; ZMessage incoming; int cycles = 0; var poll = ZPollItem.CreateReceiver(); var rnd = new Random(); while (true) { if (worker.PollIn(poll, out incoming, out error, Worker.PPP_TICK)) { // Get message // - 3-part envelope + content -> request // - 1-part HEARTBEAT -> heartbeat using (incoming) { // To test the robustness of the queue implementation we // simulate various typical problems, such as the worker // crashing or running very slowly. We do this after a few // cycles so that the architecture can get up and running // first: if (incoming.Count >= 3) { Console_WriteZMessage(incoming, "I: receiving reply"); cycles++; if (cycles > 3 && rnd.Next(5) == 0) { Console.WriteLine("I: simulating a crash"); return; } if (cycles > 3 && rnd.Next(3) == 0) { Console.WriteLine("I: simulating CPU overload"); Thread.Sleep(100); } Thread.Sleep(1); // Do some heavy work Console.WriteLine("I: sending reply"); worker.Send(incoming); liveness = Worker.PPP_HEARTBEAT_LIVENESS; } // When we get a heartbeat message from the queue, it means the // queue was (recently) alive, so we must reset our liveness // indicator: else if (incoming.Count == 1) { string identity = incoming[0].ReadString(); if (identity == Worker.PPP_HEARTBEAT) { Console.WriteLine("I: receiving heartbeat"); liveness = Worker.PPP_HEARTBEAT_LIVENESS; } else { Console_WriteZMessage(incoming, "E: invalid message"); } } else { Console_WriteZMessage(incoming, "E: invalid message"); } } interval = Worker.PPP_INTERVAL_INIT; } else { if (error == ZError.ETERM) { break; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } } if (error == ZError.EAGAIN) { // If the queue hasn't sent us heartbeats in a while, destroy the // socket and reconnect. This is the simplest most brutal way of // discarding any messages we might have sent in the meantime: if (--liveness == 0) { Console.WriteLine("W: heartbeat failure, can't reach queue"); Console.WriteLine("W: reconnecting in {0} ms", interval); Thread.Sleep(interval); if (interval < Worker.PPP_INTERVAL_MAX) { interval *= 2; } else { Console.WriteLine("E: interrupted"); break; } worker.Dispose(); if (null == (worker = PPWorker_CreateZSocket(context, name, out error))) { if (error == ZError.ETERM) { break; // Interrupted } throw new ZException(error); } liveness = Worker.PPP_HEARTBEAT_LIVENESS; } } // Send heartbeat to queue if it's time if (DateTime.UtcNow > heartbeat_at) { heartbeat_at = DateTime.UtcNow + Worker.PPP_HEARTBEAT_INTERVAL; Console.WriteLine("I: sending heartbeat"); using (var outgoing = new ZFrame(Worker.PPP_HEARTBEAT)) { worker.Send(outgoing); } } } } finally { if (worker != null) { worker.Dispose(); worker = null; } } } }
public static void MSReader(string[] args) { // // Reading from multiple sockets // This version uses a simple recv loop // // Author: metadings // using (var context = new ZContext()) using (var receiver = new ZSocket(context, ZSocketType.PULL)) using (var subscriber = new ZSocket(context, ZSocketType.SUB)) { // Connect to task ventilator receiver.Connect("tcp://127.0.0.1:5557"); // Connect to weather server subscriber.Connect("tcp://127.0.0.1:5556"); subscriber.SetOption(ZSocketOption.SUBSCRIBE, "10001 "); // Process messages from both sockets // We prioritize traffic from the task ventilator ZError error; ZFrame frame; while (true) { if (null != (frame = receiver.ReceiveFrame(ZSocketFlags.DontWait, out error))) { // Process task } else { if (error == ZError.ETERM) { return; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } } if (null != (frame = subscriber.ReceiveFrame(ZSocketFlags.DontWait, out error))) { // Process weather update } else { if (error == ZError.ETERM) { return; // Interrupted } if (error != ZError.EAGAIN) { throw new ZException(error); } } // No activity, so sleep for 1 msec Thread.Sleep(1); } } }