public static void WUProxy(string[] args) { // // Weather proxy device using (var context = new ZContext()) using (var frontend = new ZSocket(context, ZSocketType.XSUB)) using (var backend = new ZSocket(context, ZSocketType.XPUB)) { // Frontend is where the weather server sits string localhost = "tcp://127.0.0.1:5556"; Console.WriteLine("I: Connecting to {0}", localhost); frontend.Connect(localhost); // Backend is our public endpoint for subscribers foreach (IPAddress address in WUProxy_GetPublicIPs()) { var tcpAddress = string.Format("tcp://{0}:8100", address); Console.WriteLine("I: Binding on {0}", tcpAddress); backend.Bind(tcpAddress); var epgmAddress = string.Format("epgm://{0};239.192.1.1:8100", address); Console.WriteLine("I: Binding on {0}", epgmAddress); backend.Bind(epgmAddress); } using (var subscription = ZFrame.Create(1)) { subscription.Write(new byte[] { 0x1 }, 0, 1); backend.Send(subscription); } // Run the proxy until the user interrupts us ZContext.Proxy(frontend, backend); } }
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 frame = ZFrame.Create(8); var bytes = new byte[8]; using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) { rng.GetBytes(bytes); } frame.Write(bytes, 0, 8); if (!publisher.SendFrame(frame, out error)) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } Thread.Sleep(1); } } }
static void Main(string[] args) { // The publisher sends random messages starting with A-J: using (var context = new ZContext()) using (var publisher = new ZSocket(context, ZSocketType.PUB)) { publisher.Bind("tcp://*:60000"); ZError error; while (true) { var frame = ZFrame.Create(8); var bytes = new byte[8]; using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) { //用一个随机值填充数组。 rng.GetBytes(bytes); } Console.WriteLine("Frame Content: {0}", bytes.ToHexString()); frame.Write(bytes, 0, 8); if (!publisher.SendFrame(frame, out error)) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } Thread.Sleep(1); } } }
// // Broker peering simulation (part 1) // Prototypes the state flow // // Author: metadings // public static void Peering1(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) { 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 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]; using (var context = new ZContext()) { ZSocket requester = null; try { // using (requester) 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); if (!requester.Send(outgoing, out error)) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } 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); if (!requester.Send(outgoing, out error)) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } continue; } if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } } } finally { if (requester != null) { requester.Dispose(); requester = null; } } } }
static void Main(string[] args) { var options = new Options(); var parser = new CommandLineParser(new CommandLineParserSettings(Console.Error)); if (!parser.ParseArguments(args, options)) { Console.ReadLine(); throw new ArgumentException(); } // // Weather proxy device // // Author: metadings // using (var context = new ZContext()) using (var frontend = new ZSocket(context, ZSocketType.XSUB)) using (var backend = new ZSocket(context, ZSocketType.XPUB)) { // Frontend is where the weather server sits foreach (var frontendBindEndPoint in options.FrontendBindEndPoints) { var ipPortProtocal = frontendBindEndPoint.Split(':'); var ip = ipPortProtocal[0]; var port = ipPortProtocal[1]; var protocal = ipPortProtocal[2]; switch (protocal.ToLower()) { case "pgm": var pgmAddress = string.Format("pgm://;239.192.1.1:{0}", port); Console.WriteLine("I: Connecting to FrontEndPoint {0}...", pgmAddress); frontend.Connect(pgmAddress); break; case "epgm": var epgmAddress = string.Format("epgm://;239.192.1.1:{0}", port); Console.WriteLine("I: Connecting to FrontEndPoint {0}...", epgmAddress); frontend.Connect(epgmAddress); break; default: { string frontHost = string.Format("{0}://{1}:{2}", protocal, ip, port); Console.WriteLine("I: Connecting to FrontEndPoint: {0}", frontHost); frontend.Connect(frontHost); } break; } } // Backend is our public endpoint for subscribers //Proxy 还可以装换协议,把前边的unicast转换为 multicast foreach (var backendBindEndPoint in options.BackendBindEndPoints) { var ipPortProtocal = backendBindEndPoint.Split(':'); var ip = ipPortProtocal[0]; var port = ipPortProtocal[1]; var protocal = ipPortProtocal[2]; var tcpAddress = string.Format("tcp://{0}:{1}", ip, port); var pgmAddress = string.Format("pgm://{0};239.192.1.1:{1}", ip, port); var epgmAddress = string.Format("epgm://{0};239.192.1.1:{1}", ip, port); switch (protocal.ToLower()) { case "pgm": Console.WriteLine("I: Binding on {0}", epgmAddress); backend.Bind(epgmAddress); break; case "epgm": Console.WriteLine("I: Binding on {0}", epgmAddress); backend.Bind(epgmAddress); break; case "tcp": { Console.WriteLine("I: Binding on {0}", tcpAddress); backend.Bind(tcpAddress); } break; default: { Console.WriteLine("I: Binding on {0}", epgmAddress); backend.Bind(epgmAddress); Console.WriteLine("I: Binding on {0}", tcpAddress); backend.Bind(tcpAddress); break; } } } using (var newFrame = ZFrame.Create(1)) { newFrame.Write(new byte[] { 0x1 }, 0, 1); backend.Send(newFrame); } //here, it's more like a bridge // Run the proxy until the user interrupts us ZContext.Proxy(frontend, backend); } }
public void LPClient() { string name = "ZMQsocket"; using (var context = new ZContext()) { ZSocket requester = null; try { // using (requester) ZError error; if (null == (requester = LPClient_CreateZSocket(context, name, out error))) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } int sequence = 10; 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); if (!requester.Send(outgoing, out error)) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } ZMessage incoming; // 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 (incoming_sequence >= 0 && incoming_sequence <= 9) { TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": I: Сервер ответил: ({0}) \n", incoming_sequence)); } else { TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": E: Ошибка на стороне сервера: ({0}) \n", incoming_sequence)); } retries_left = LPClient_RequestRetries; break; } } else { if (error == ZError.EAGAIN) { if (--retries_left == 0) { TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": E: Сервер недоступен \n")); break; } TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": W: Нет ответа от сервера, переподключение... \n")); // 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); } TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": I: Переподключение \n")); // Send request again, on new socket using (var outgoing = ZFrame.Create(4)) { outgoing.Write(sequence); if (!requester.Send(outgoing, out error)) { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } continue; } if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } } catch { TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": E: Ошибка запроса. \n")); } finally { if (requester != null) { requester.Dispose(); requester = null; } } } }