static int FLClient1_MAX_RETRIES = 3; // Before we abandon public static void FLClient1(IDictionary <string, string> dict, string[] args) { // // Freelance client - Model 1 // Uses REQ socket to query one or more services // // Authors: Pieter Hintjens, Uli Riehm // if (args == null || args.Length < 1) { Console.WriteLine("I: syntax: {0} FLClient1 [endpoint]", AppDomain.CurrentDomain.FriendlyName); return; } // The client uses a Lazy Pirate strategy if it only has one server to talk // to. If it has two or more servers to talk to, it will try each server just // once: using (var context = ZContext.Create()) using (var request = new ZFrame("Hello World")) { ZFrame reply = null; if (args.Length == 1) { // For one endpoint, we retry N times string endpoint = args[0]; for (int retries = 0; retries < FLClient1_MAX_RETRIES; ++retries) { if (null != (reply = FLClient1_TryRequest(context, endpoint, request))) { break; // Successful } Console.WriteLine("W: no response from {0}, retrying...", endpoint); } } else { // For multiple endpoints, try each at most once for (int endpoint_nbr = 0; endpoint_nbr < args.Length; ++endpoint_nbr) { string endpoint = args[endpoint_nbr]; if (null != (reply = FLClient1_TryRequest(context, endpoint, request))) { break; // Successful } Console.WriteLine("W: no response from {0}, retrying...", endpoint); } } if (reply != null) { Console.WriteLine("Service is running OK"); } } }
public static void Console_WriteZFrame(string format, ZFrame frame, params object[] data) { var renderer = new StringBuilder(); var list = new List <object>(data); // here the renderer renderer.Append(format); renderer.Append(": "); renderer.Append("{"); renderer.Append(0 + data.Length); renderer.Append("}"); // now the message frame.Position = 0; if (frame.Length == 0) { list.Add("0"); } else { list.Add(frame.ReadString()); } frame.Position = 0; Console.WriteLine(renderer.ToString(), list.ToArray()); }
public void Execute(ProcessNode currentNode, ProcessNode previousNode) { string endpoint = "tcp://127.0.0.1:5556"; // Create using (var context = new ZContext()) using (var requester = new ZSocket(context, ZSocketType.REQ)) { // Connect requester.Connect(endpoint); string requestText = "Do some work"; Console.WriteLine("Request {0}", requestText); // Send requester.Send(new ZFrame(requestText)); // Receive using (ZFrame reply = requester.ReceiveFrame()) { Console.WriteLine("Received: {0} ", reply.ReadString()); } currentNode.Done(); } }
static void Main(string[] args) { Console.WriteLine("10 seconds worker server"); // Create using (var context = new ZContext()) using (var responder = new ZSocket(context, ZSocketType.REP)) { // Bind responder.Bind("tcp://*:5556"); while (true) { // Receive using (ZFrame request = responder.ReceiveFrame()) { Console.WriteLine("Received {0}", request.ReadString()); // Do some work Thread.Sleep(10000); // Send Console.WriteLine("Sending Work Done"); responder.Send(new ZFrame("Work Done")); } } } }
public VehicleRecogResult GetVehicleByPic(string imageFileName) { VehicleRecogResult vehicleResults = new VehicleRecogResult(); using (var requester = new ZSocket(context, ZSocketType.REQ)) { requester.Connect("tcp://127.0.0.1:50559"); string imagepath = imageFileName; if (File.Exists(imagepath)) { Guid guid = Guid.NewGuid(); DataTypes.VehicleInfo info = new DataTypes.VehicleInfo(); info.Id = "11111"; info.Imagepath = (imagepath); info.Uuid = guid.ToString().Replace("-", ""); ZMessage zMsg = new ZMessage(); zMsg.Add(new ZFrame(info.ToByteArray())); requester.Send(zMsg); using (ZFrame reply = requester.ReceiveFrame()) { DataTypes.VehicleInfo msg2 = new DataTypes.VehicleInfo(); msg2.MergeFrom(reply.Read()); vehicleResults = JsonConvert.DeserializeObject <VehicleRecogResult>(msg2.Jsonresult); //Console.WriteLine(" Received: {0}!", msg2.Jsonresult); } } } return(vehicleResults); }
private void ReceiveDataHandler() { while (Enabled) { // Receive data from the socket using (ZMessage message = m_zeroMQClient.Provider.ReceiveMessage()) { // Dealer socket should have removed identity frame already, should be left // with delimiter and data payload frames if (message.Count == 2) { // Get the data payload frame ZFrame frame = message[1]; m_zeroMQClient.BytesReceived = (int)frame.Length; if (m_zeroMQClient.ReceiveBufferSize < m_zeroMQClient.BytesReceived) { m_zeroMQClient.SetReceiveBuffer(m_zeroMQClient.BytesReceived); } frame.Read(m_zeroMQClient.ReceiveBuffer, 0, m_zeroMQClient.BytesReceived); m_zeroMQClient.Statistics.UpdateBytesReceived(m_zeroMQClient.BytesReceived); // Notify consumer of received data OnReceiveDataComplete(m_zeroMQClient.ReceiveBuffer, m_zeroMQClient.BytesReceived); } } } }
// Send message to the command server public bool SendCommandMessage(ref Message msg, out string error) { error = ""; try { bool bOK = false; // Load message topic and data msg.SerializeMessageToBuffer(out byte[] buffer); // Send to command server endpoint using (var client = new ZSocket(ZSocketType.REQ)) { client.SendTimeout = new TimeSpan(0, 0, 5); client.ReceiveTimeout = new TimeSpan(0, 0, 5); client.Connect(Settings.Instance.CmdClientUri); ZFrame frame = new ZFrame(buffer); bOK = client.Send(frame, out ZError zerror); if (bOK) { using (ZFrame reply = client.ReceiveFrame()) { byte[] resultBuffer = reply.Read(); msg = Message.DeserializeBufferToMessage(resultBuffer); } } } return(bOK); } catch (Exception ex) { error = $"Settings::Initialize error {ex.Message}"; Debug.WriteLine(error); } return(false); }
/// <summary> /// Sends a requestion and waits for the response /// </summary> /// <param name="req">The request to be sent to MegaMol</param> /// <param name="timeout">The timeout when the function will throw an exception</param> /// <returns>The response answer by MegaMol</returns> public void Send(Request req, TimeSpan timeout) { if (req == null) { throw new ArgumentNullException("req"); } socket.ReceiveTimeout = timeout; socket.SendTimeout = timeout; ZFrame reqData = req.MakeZMQRequest(); if (reqData == null) { throw new ArgumentException("req seemed illegal"); } socket.Send(reqData); //Response resp = null; //using (ZFrame reply = socket.ReceiveFrame()) { // Response r = new Response(); // r.Request = req; // set request first, because that object is required to parse the answer // r.fromZFrameString(reply.ReadString(Encoding.UTF8)); // resp = r; //} //return resp; }
public static void Move(string Direction) { string ServerAdress = "tcp://127.0.0.1:5" + Port + "6"; using (var context = new ZContext()) using (var requester = new ZSocket(context, ZSocketType.REQ)) { requester.Connect(ServerAdress); requester.Send(new ZFrame(PlayerName + ";" + Direction)); using (ZFrame reply = requester.ReceiveFrame()) { if (reply.ReadString() == "Accepted") { Console.WriteLine("Accepted"); } else { Console.WriteLine("error"); MessageBox.Show("Error (maybe name is already taken)", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
void ReadMessagesThread() { string uri = Settings.Instance.SubscribeUri; using (var subscriber = new ZSocket(ZSocketType.SUB)) { subscriber.ReceiveTimeout = new TimeSpan(0, 0, 5); subscriber.Connect(uri); foreach (var topic in Topics) { subscriber.Subscribe(topic); } do { try { using (ZFrame reply = subscriber.ReceiveFrame()) { byte[] tempBuffer = reply.Read(); var msg = Message.DeserializeBufferToMessage(tempBuffer); MessageCallback?.Invoke(msg); } } catch (Exception ex) { Debug.WriteLine($"ReadMessagesThread Exception {ex.Message}"); } }while (WaitEvent.WaitOne(1) == false); } }
public static void GetServerPort() { string ServerAdress = "tcp://127.0.0.1:5000"; using (var context = new ZContext()) using (var requester = new ZSocket(context, ZSocketType.REQ)) { requester.Connect(ServerAdress); requester.Send(new ZFrame("New")); using (ZFrame reply = requester.ReceiveFrame()) { String Answer = reply.ReadString(); if (Answer != "Error") { Console.WriteLine("Accept"); Port = Answer; MessageBox.Show("Connecting to " + Port + "...", "Connecting...", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { Console.WriteLine("error"); MessageBox.Show("Error (Get New Port)", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
public static void Auth(string Name) { GetServerPort(); string ServerAdress = "tcp://127.0.0.1:5" + Port + "5"; using (var context = new ZContext()) using (var requester = new ZSocket(context, ZSocketType.REQ)) { requester.Connect(ServerAdress); requester.Send(new ZFrame(Name)); using (ZFrame reply = requester.ReceiveFrame()) { if (reply.ReadString() == "Accepted") { Console.WriteLine("Accept"); PlayerName = Name; inpWindow.Close(); } else { Console.WriteLine("error"); MessageBox.Show("Error (maybe name is already taken)", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
static void Main(string[] args) { // //Hello World Client // //Author: metadings // //Create //using(var context = new ZContext()) using (var requester = new ZSocket(ZSocketType.REQ)) { //Connect requester.Connect("tcp://127.0.0.1:5555"); for (int n = 0; n < 10; n++) { //Message string requestText = "Hello my friend"; Console.WriteLine("Sending {0}...", requestText); //Send requester.Send(new ZFrame(requestText)); //Receive using (ZFrame reply = requester.ReceiveFrame()) { Console.WriteLine("Received {0} {1}!", requestText, reply.ReadString()); Console.ReadKey(); } } } }
public void ReceiveJson() { while (Thread.CurrentThread.IsAlive) { String request = null; if (this.binded) { try { ZFrame frame = this.socket.ReceiveFrame(); request = frame.ReadString(); String reply = this.UpdateParams(request); ZFrame message = new ZFrame(reply); this.socket.Send(message); } catch (ZException e) { request = "Cannot receive message: " + e.Message; } } else { request = "Cannot receive message: Not connected"; } } }
static void Main(string[] args) { string name = "World"; // Create // using (var context = new ZContext()) using (var responder = new ZSocket(ZSocketType.REP)) { // Bind responder.Bind("tcp://*:5555"); while (true) { // Receive using (ZFrame request = responder.ReceiveFrame()) { Console.WriteLine("Received {0}", request.ReadString()); // Do some work Thread.Sleep(1); // Send responder.Send(new ZFrame(name)); } } } }
/// <summary> /// 响应 服务器端 /// </summary> /// <param name="port"></param> /// <param name="messageHandler">不能为null,否则抛出异常,MessageHandler不能抛出异常</param> public static void ReqServer(int port, Func <String, String> messageHandler) { //ZContext实例 using (ZContext context = new ZContext()) { //ZSocket实例 响应 using (ZSocket responder = new ZSocket(context, ZSocketType.REP)) { ZError zError = null; bool result = responder.Bind($"tcp://*:{port}", out zError); while (isRunning) { //接收消息 using (ZFrame request = responder.ReceiveFrame()) { //Response socket always reply to the last client that sends a message. String msg = request.ReadString(Encoding.UTF8); String resp = messageHandler(msg); responder.Send(new ZFrame(resp, Encoding.UTF8)); } } } } }
// .split service methods // Here is the implementation of the methods that work on a service: // Lazy constructor that locates a service by name or creates a new // service if there is no service already with that name. public Service RequireService(ZFrame serviceFrame) { if (serviceFrame == null) { throw new InvalidOperationException(); } string name = serviceFrame.ToString(); Service service; if (Services.ContainsKey(name)) { service = Services[name]; } else { service = new Service(this, name); Services[name] = service; //zhash_freefn(self->workers, id_string, s_worker_destroy); if (Verbose) { "I: added service: '{0}'".DumpString(name); } } return(service); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); using (var publisher = new ZSocket(ZSocketType.PUB)) { string address = "tcp://*:5556"; Console.WriteLine("I: Publisher.Bind'ing on {0}", address); publisher.Bind(address); // Initialize random number generator var rnd = new Random(); while (true) { // Get values that will fool the boss int zipcode = rnd.Next(99999); int temperature = rnd.Next(-55, +45); // Send message to all subscribers var update = string.Format("{0:D5} {1}", zipcode, temperature); using (var updateFrame = new ZFrame(update)) { publisher.Send(updateFrame); } } } }
// .split worker methods // Here is the implementation of the methods that work on a worker: // Lazy constructor that locates a worker by identity, or creates a new // worker if there is no worker already with that identity. public Worker RequireWorker(ZFrame identity) { if (identity == null) { throw new InvalidOperationException(); } string idString; using (var tstfrm = identity.Duplicate()) { idString = tstfrm.Read().ToHexString(); } Worker worker = Workers.ContainsKey(idString) ? Workers[idString] : null; if (worker == null) { worker = new Worker(idString, this, identity); Workers[idString] = worker; if (Verbose) { "I: registering new worker: '{0}'".DumpString(idString); } } return(worker); }
public static void HWClient(IDictionary <string, string> dict, string[] args) { // // Hello World client // // Author: metadings // // Create using (var context = ZContext.Create()) using (var requester = ZSocket.Create(context, ZSocketType.REQ)) { // Connect requester.Connect("tcp://127.0.0.1:5555"); for (int n = 0; n < 10; ++n) { string requestText = "Hello"; Console.Write("Sending {0}...", requestText); // Send using (var request = new ZFrame(requestText)) { requester.Send(request); } // Receive using (ZFrame reply = requester.ReceiveFrame()) { Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString()); } } } }
public static void Main(string[] args) { if (args == null || args.Length < 1) { Console.WriteLine(" Клиент подключен к адресу"); Console.WriteLine(" tcp://192.168.0.102:5555"); Console.WriteLine(); args = new string[] { "tcp://192.168.0.102:5555" }; } string endpoint = args[0]; // Create using (var context = new ZContext()) using (var requester = new ZSocket(context, ZSocketType.REQ)) { // Connect requester.Connect(endpoint); Console.WriteLine("Отправь сообщение: \n"); string requestText = Console.ReadLine(); Console.WriteLine("Sending {0}…", requestText); Console.WriteLine(); // Send requester.Send(new ZFrame(requestText)); // Receive using (ZFrame reply = requester.ReceiveFrame()) { Console.WriteLine(" Вы отправили сообщение: {0}, Длина сообщения: {1}\n", requestText, reply.ReadString()); } } }
static void Main(string[] args) { Console.WriteLine("BPMN worker server"); // Create using (var context = new ZContext()) using (var responder = new ZSocket(context, ZSocketType.REP)) { // Bind responder.Bind("tcp://*:5555"); while (true) { // Receive using (ZFrame request = responder.ReceiveFrame()) { var flow = request.ReadString(); if (flow.StartsWith("<?xml")) //Just for demo purposes { var p = new Process(new MemoryStream(Encoding.UTF8.GetBytes(flow))); var processInstance = p.NewProcessInstance(); processInstance.SetDefaultHandlers(); processInstance.SetHandler("task", new ZMQTaskHandler()); //processInstance.SetHandler("endEvent", new ZMQEndHandler(responder)); processInstance.Start(new Dictionary <string, object>()); } responder.Send(new ZFrame("Work Done")); } } } }
private static void Main(string[] args) { try { var options = new Options(); var parser = new CommandLineParser(new CommandLineParserSettings(Console.Error)); if (!parser.ParseArguments(args, options)) { Environment.Exit(1); } using (var context = ZContext.Create()) { using (var socket = new ZSocket(context, ZSocketType.PUSH)) { foreach (var endPoint in options.BindEndPoints) { socket.Bind(endPoint); } long msgCptr = 0; var msgIndex = 0; while (true) { if (msgCptr == long.MaxValue) { msgCptr = 0; } msgCptr++; if (options.MaxMessage >= 0) { if (msgCptr > options.MaxMessage) { break; } } if (msgIndex == options.AltMessages.Count()) { msgIndex = 0; } var msg = options.AltMessages[msgIndex++].Replace("#nb#", msgCptr.ToString("d2")); Thread.Sleep(options.Delay); Console.WriteLine("Pushing: " + msg); var msgFrame = new ZFrame(msg, Encoding.UTF8); socket.Send(msgFrame); } } } } catch (Exception exp) { Console.WriteLine(exp.Message); } }
private static void Main(string[] args) { var options = new Options(); var parser = new CommandLineParser(new CommandLineParserSettings(Console.Error)); if (!parser.ParseArguments(args, options)) { Environment.Exit(1); } using (var context = ZContext.Create()) { using (var socket = new ZSocket(context, ZSocketType.REP)) { foreach (var bindEndPoint in options.BindEndPoints) { socket.Bind(bindEndPoint); } while (true) { Thread.Sleep(options.Delay); var rcvdFrame = socket.ReceiveFrame(); var rcvdMsg = rcvdFrame.ReadString(Encoding.UTF8); Console.WriteLine("Received: " + rcvdMsg); var replyMsg = options.ReplyMessage.Replace("#msg#", rcvdMsg); var replyFrame = new ZFrame(replyMsg); Console.WriteLine("Sending : " + replyMsg + Environment.NewLine); socket.Send(replyFrame); } } } }
public static void Main(string[] args) { var endpoint = "tcp://191.232.181.23:5560"; using (var context = new ZContext()) using (var socket = new ZSocket(context, ZSocketType.REQ)) { Console.WriteLine($"Conectando-se ao endpoint {endpoint}"); socket.Connect(endpoint); var count = 1; while (count < 10001) { var frame = new ZFrame(count.ToString()); socket.Send(frame); var reply = socket.ReceiveFrame(); Console.WriteLine($"Resposta {reply.ToString()} recebida"); count++; } Console.ReadLine(); } }
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()) { //Console.WriteLine($"worker receive data: {frame.ReadString()}"); var 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 static void RRClient(IDictionary <string, string> dict, string[] args) { // // Hello World client // Connects REQ socket to tcp://localhost:5559 // Sends "Hello" to server, expects "World" back // // Authors: Pieter Hintjens, Uli Riehm // // Socket to talk to server using (var context = ZContext.Create()) using (var requester = ZSocket.Create(context, ZSocketType.REQ)) { requester.Connect("tcp://127.0.0.1:5559"); for (int n = 0; n < 10; ++n) { using (var request = new ZFrame("Hello")) { requester.Send(request); } using (ZFrame reply = requester.ReceiveFrame()) { Console.WriteLine("Hello {0}!", reply.ReadString()); } } } }
static ZFrame FLClient1_TryRequest(ZContext context, string endpoint, ZFrame request) { Console.WriteLine("I: trying echo service at {0}...", endpoint); using (var client = ZSocket.Create(context, ZSocketType.REQ)) { client.Connect(endpoint); // Send request, wait safely for reply using (var message = ZFrame.CopyFrom(request)) { client.Send(message); } var poll = ZPollItem.CreateReceiver(); ZError error; ZMessage incoming; if (client.PollIn(poll, out incoming, out error, FLClient1_REQUEST_TIMEOUT)) { return(incoming[0]); } } return(null); }
public static void RRClient(string[] args) { // // Hello World client // Connects REQ socket to tcp://127.0.0.1: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 MsgServer(string name) { int requestCount = 0; using (var context = new ZContext()) using (var responder = new ZSocket(context, ZSocketType.REP)) { responder.Bind("tcp://*:5555"); while (true) { // Receive using (ZFrame request = responder.ReceiveFrame()) { ++requestCount; Console.WriteLine("Hifrend received request #{0}: {1}", requestCount, request.ReadString()); // Do some work Thread.Sleep(1); responder.Send(new ZFrame(name)); } } } }
/// <summary> /// Forwards replies from the backend socket to the frontend socket. /// </summary> protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error) { error = default(ZError); message = null; // receiving scope // DEALER: normal movemsg ZMessage incoming = null; if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error)) { return false; } using (incoming) { // STREAM: write frames: identity, body, identity, empty // Read identity int ic = (int)incoming[0].Length; var identityBytes = new byte[ic]; incoming[0].Read(identityBytes, 0, ic); // Remove DEALER's delimiter incoming.RemoveAt(1); // Append Identity frame var identity0 = new ZFrame(identityBytes); incoming.Add(identity0); // Append STREAM's empty delimiter frame incoming.Add(new ZFrame()); if (!SendMsg(FrontendSocket, incoming, out error)) { return false; } } return true; }
/// <summary> /// /// </summary> /// <param name="idString"></param> /// <param name="broker"></param> /// <param name="identity">will be dublicated inside the constructor</param> public Worker(string idString, Broker broker, ZFrame identity) { Broker = broker; IdString = idString; Identity = identity.Duplicate(); }
// .split worker methods // Here is the implementation of the methods that work on a worker: // Lazy constructor that locates a worker by identity, or creates a new // worker if there is no worker already with that identity. public Worker RequireWorker(ZFrame identity) { if (identity == null) throw new InvalidOperationException(); string idString; using (var tstfrm = identity.Duplicate()) { idString = tstfrm.Read().ToHexString(); } Worker worker = Workers.ContainsKey(idString) ? Workers[idString] : null; if (worker == null) { worker = new Worker(idString, this, identity); Workers[idString] = worker; if(Verbose) "I: registering new worker: '{0}'".DumpString(idString); } return worker; }
// .split service methods // Here is the implementation of the methods that work on a service: // Lazy constructor that locates a service by name or creates a new // service if there is no service already with that name. public Service RequireService(ZFrame serviceFrame) { if(serviceFrame == null) throw new InvalidOperationException(); string name = serviceFrame.ToString(); Service service; if (Services.ContainsKey(name)) { service = Services[name]; } else { service = new Service(this, name); Services[name] = service; //zhash_freefn(self->workers, id_string, s_worker_destroy); if (Verbose) "I: added service: '{0}'".DumpString(name); } return service; }
// .split broker client_msg method // Process a request coming from a client. We implement MMI requests // directly here (at present, we implement only the mmi.service request): public void ClientMsg(ZFrame sender, ZMessage msg) { // service & body if(msg.Count < 2) throw new InvalidOperationException(); using (ZFrame serviceFrame = msg.Pop()) { Service service = RequireService(serviceFrame); // Set reply return identity to client sender msg.Wrap(sender.Duplicate()); //if we got a MMI Service request, process that internally if (serviceFrame.Length >= 4 && serviceFrame.ToString().StartsWith("mmi.")) { string returnCode; if (serviceFrame.ToString().Equals("mmi.service")) { string name = msg.Last().ToString(); returnCode = Services.ContainsKey(name) && Services[name].Workers > 0 ? "200" : "404"; } else returnCode = "501"; var client = msg.Unwrap(); msg.Clear(); msg.Add(new ZFrame(returnCode)); msg.Prepend(serviceFrame); msg.Prepend(new ZFrame(MdpCommon.MDPC_CLIENT)); msg.Wrap(client); Socket.Send(msg); } else { // Else dispatch the message to the requested Service service.Dispatch(msg); } } }
// .split broker worker_msg method // This method processes one READY, REPLY, HEARTBEAT, or // DISCONNECT message sent to the broker by a worker: public void WorkerMsg(ZFrame sender, ZMessage msg) { if(msg.Count < 1) // At least, command throw new InvalidOperationException(); ZFrame command = msg.Pop(); //string id_string = sender.ReadString(); bool isWorkerReady; //string id_string; using (var sfrm = sender.Duplicate()) { var idString = sfrm.Read().ToHexString(); isWorkerReady = Workers.ContainsKey(idString); } Worker worker = RequireWorker(sender); using (msg) using (command) { if (command.StrHexEq(MdpCommon.MdpwCmd.READY)) { if (isWorkerReady) // Not first command in session worker.Delete(true); else if (command.Length >= 4 && command.ToString().StartsWith("mmi.")) // Reserd servicee name worker.Delete(true); else { // Attach worker to service and mark as idle using (ZFrame serviceFrame = msg.Pop()) { worker.Service = RequireService(serviceFrame); worker.Service.Workers++; worker.Waiting(); } } } else if (command.StrHexEq(MdpCommon.MdpwCmd.REPLY)) { if (isWorkerReady) { // Remove and save client return envelope and insert the // protocol header and service name, then rewrap envelope. ZFrame client = msg.Unwrap(); msg.Prepend(new ZFrame(worker.Service.Name)); msg.Prepend(new ZFrame(MdpCommon.MDPC_CLIENT)); msg.Wrap(client); Socket.Send(msg); worker.Waiting(); } else { worker.Delete(true); } } else if (command.StrHexEq(MdpCommon.MdpwCmd.HEARTBEAT)) { if (isWorkerReady) { worker.Expiry = DateTime.UtcNow + MdpCommon.HEARTBEAT_EXPIRY; } else { worker.Delete(true); } } else if (command.StrHexEq(MdpCommon.MdpwCmd.DISCONNECT)) worker.Delete(false); else { msg.DumpZmsg("E: invalid input message"); } } }
// .split broker client_msg method // Process a request coming from a client. We implement MMI requests // directly here (at present, we implement only the mmi.service request): public void ClientMsg(ZFrame sender, ZMessage msg) { // service & body if(msg.Count < 2) throw new InvalidOperationException(); using (ZFrame serviceFrame = msg.Pop()) { Service service = RequireService(serviceFrame); // Set reply return identity to client sender msg.Wrap(sender.Duplicate()); //if we got a MMI Service request, process that internally if (serviceFrame.Length >= 4 && serviceFrame.ToString().StartsWith("mmi.")) { string returnCode; if (serviceFrame.ToString().Equals("mmi.service")) { string name = msg.Last().ToString(); returnCode = Services.ContainsKey(name) && Services[name].Workers > 0 ? "200" : "400"; } else returnCode = "501"; using (var resetableFrame = msg.Pop()) { msg.Prepend(new ZFrame(returnCode)); } //ToDo check c implementation throw new NotImplementedException("ToDo: fix this section, never tested. contains errors mmi services never called with the mdclient/mdbroker/mdworker examples"); //## following code has some errors // Remove & save client return envelope and insert the // protocol header and Service name, then rewrap envelope. ZFrame client = msg.Unwrap(); msg.Prepend(serviceFrame); msg.Prepend(new ZFrame(MdpCommon.MDPC_CLIENT)); msg.Wrap(client); Socket.Send(msg); } else { // Else dispatch the message to the requested Service service.Dispatch(msg); } } }