public void Shutdown_Twice() { using (var context = new ZContext()) { context.Shutdown(); context.Shutdown(); } }
public static void Run(CancellationToken cancellationToken) { using (var context = new ZContext()) using (var sink = new ZSocket(context, ZSocketType.PULL)) { if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Sink cancelled..."); context.Shutdown(); cancellationToken.ThrowIfCancellationRequested(); } Console.WriteLine("Sink started...."); sink.Bind("tcp://*:5558"); // Wait for start of batch ZError error; ZFrame frame = sink.ReceiveFrame(out error); if (null == frame) { if (error != null) { throw new ZException(error); } } while (!cancellationToken.IsCancellationRequested) { using (frame = sink.ReceiveFrame(out error)) { if (frame == null) { if (Equals(error, ZError.EAGAIN)) { Thread.Sleep(1); continue; } throw new ZException(error); } string item = frame.ReadString(); receivedList.Add(item); } if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Sink cancelled..."); context.Shutdown(); cancellationToken.ThrowIfCancellationRequested(); } } } }
public void Run(CancellationToken cancellationToken) { using (var context = new ZContext()) using (var receiver = new ZSocket(context, ZSocketType.PULL)) using (var sink = new ZSocket(context, ZSocketType.PUSH)) { if (cancellationToken.IsCancellationRequested) { Console.WriteLine($"Woker{workerId} cancelled...."); context.Shutdown(); cancellationToken.ThrowIfCancellationRequested(); } receiver.Connect("tcp://127.0.0.1:5557"); sink.Connect("tcp://127.0.0.1:5558"); Console.WriteLine($"Worker{workerId} started...."); while (!cancellationToken.IsCancellationRequested) { int workload; ZError error; using (ZFrame frame = receiver.ReceiveFrame(out error)) { if (frame == null) { if (Equals(error, ZError.EAGAIN)) { Thread.Sleep(1); continue; } throw new ZException(error); } workload = frame.ReadInt32(); } sink.SendFrame(new ZFrame($"worker{workerId} workload:{workload}")); ProcessedMessages++; if (cancellationToken.IsCancellationRequested) { Console.WriteLine($"Woker{workerId} cancelled...."); context.Shutdown(); cancellationToken.ThrowIfCancellationRequested(); } Thread.SpinWait(100); } } }
// added ShutdownContext, to call shutdown in main method. public void ShutdownContext() { if (_context != null) { _context.Shutdown(); } }
public void Dispose() { loop = false; sink.Close(); sink.Dispose(); context.Shutdown(); context.Dispose(); }
public void Dispose() { sender.Close(); sink.Close(); sender.Dispose(); sink.Dispose(); context.Shutdown(); context.Dispose(); }
public void Dispose() { foreach (var s in Sockets) { s.SetOption(ZSocketOption.LINGER, 0); s.Close(); s.Dispose(); } context.Shutdown(); context.Terminate(); context.Dispose(); }
public static void Run(int messages, CancellationToken cancellationToken) { using (var context = new ZContext()) using (var sender = new ZSocket(context, ZSocketType.PUSH)) using (var sink = new ZSocket(context, ZSocketType.PUSH)) { if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Producer cancelled..."); context.Shutdown(); cancellationToken.ThrowIfCancellationRequested(); } Console.WriteLine($"Producer started...."); sender.Bind("tcp://*:5557"); sink.Connect("tcp://127.0.0.1:5558"); // The first message is "0" and signals start of batch sink.Send(new byte[] { 0x00 }, 0, 1); int i = 1; for (; i <= messages; ++i) { byte[] action = BitConverter.GetBytes(i); sender.Send(action, 0, action.Length); if (cancellationToken.IsCancellationRequested) { Console.WriteLine("Producer cancelled..."); context.Shutdown(); cancellationToken.ThrowIfCancellationRequested(); } } } }
static void Espresso_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"); ZError error; ZFrame frame; while (true) { if (null != (frame = listener.ReceiveFrame(out error))) { using (frame) { byte first = frame.ReadAsByte(); var rest = new byte[9]; frame.Read(rest, 0, rest.Length); Console.WriteLine("{0} {1}", (char)first, rest.ToHexString()); if (first == 0x01) { // Subscribe } else if (first == 0x00) { // Unsubscribe context.Shutdown(); } } } else { if (error == ZError.ETERM) { return; // Interrupted } throw new ZException(error); } } } }
private void KinectAnywhereForm_FormClosing(object sender, FormClosingEventArgs e) { if (kinectSensor != null) { kinectSensor.Close(); } zmqContext.Shutdown(); DisposeSocket(pointCloudPublisher); DisposeSocket(colorFramePublisher); DisposeSocket(bodyFramePublisher); DisposeIntPtr(colorPixels); DisposeIntPtr(depthFrameData); DisposeIntPtr(camerSpacePoints); DisposeIntPtr(colorSpacePoints); }
// .until // .skip // The send method now just sends one message, without waiting for a // reply. Since we're using a DEALER socket we have to send an empty // frame at the start, to create the same envelope that the REQ socket // would normally make for us: public int Send(string service, ZMessage request, CancellationTokenSource cancellor) { if (request == null) { throw new NotImplementedException(); } if (cancellor.IsCancellationRequested || (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) { _context.Shutdown(); } // Prefix request with protocol frames // Frame 0: empty (REQ emulation) // Frame 1: "MDPCxy" (six bytes, MDP/Client x.y) // Frame 2: Service name (printable string) request.Prepend(new ZFrame(service)); request.Prepend(new ZFrame(MdpCommon.MDPC_CLIENT)); request.Prepend(new ZFrame(string.Empty)); if (Verbose) { request.DumpZmsg("I: send request to '{0}' service:", service); } ZError error; if (!Client.Send(request, out error)) { ; } { if (Equals(error, ZError.ETERM)) { cancellor.Cancel(); // Interrupted } //throw new ZException(error); } return(0); }
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 = new ZContext()) using (var server = new ZSocket(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) { if (Verbose) { 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); if (Verbose) { 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"); } } }
// .split send request and wait for reply // Here is the {{send}} method. It sends a request to the broker and gets // a reply even if it has to retry several times. It takes ownership of // the request message, and destroys it when sent. It returns the reply // message, or NULL if there was no reply after multiple attempts: public ZMessage Send(string service, ZMessage request, CancellationTokenSource cancellor) { if (request == null) { throw new InvalidOperationException(); } // Prefix request with protocol frames // Frame 1: "MDPCxy" (six bytes, MDP/Client x.y) // Frame 2: Service name (printable string) request.Prepend(new ZFrame(service)); request.Prepend(new ZFrame(MdpCommon.MDPC_CLIENT)); if (Verbose) { request.DumpZmsg("I: send request to '{0}' service:", service); } int retriesLeft = Retries; while (retriesLeft > 0 && !cancellor.IsCancellationRequested) { if (cancellor.IsCancellationRequested || (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) { _context.Shutdown(); } // Copy the Request and send on Client ZMessage msgreq = request.Duplicate(); ZError error; if (!Client.Send(msgreq, out error)) { if (Equals(error, ZError.ETERM)) { cancellor.Cancel(); break; // Interrupted } } var p = ZPollItem.CreateReceiver(); ZMessage msg; // .split body of send // On any blocking call, {{libzmq}} will return -1 if there was // an error; we could in theory check for different error codes, // but in practice it's OK to assume it was {{EINTR}} (Ctrl-C): // Poll the client Message if (Client.PollIn(p, out msg, out error, Timeout)) { // If we got a reply, process it if (Verbose) { msg.DumpZmsg("I: received reply"); } if (msg.Count < 3) { throw new InvalidOperationException(); } using (ZFrame header = msg.Pop()) if (!header.ToString().Equals(MdpCommon.MDPC_CLIENT)) { throw new InvalidOperationException(); } using (ZFrame replyService = msg.Pop()) if (!replyService.ToString().Equals(service)) { throw new InvalidOperationException(); } request.Dispose(); return(msg); } else if (Equals(error, ZError.ETERM)) { cancellor.Cancel(); break; // Interrupted } else if (Equals(error, ZError.EAGAIN)) { if (--retriesLeft > 0) { if (Verbose) { "W: no reply, reconnecting...".DumpString(); } ConnectToBroker(); } else { if (Verbose) { "W: permanent error, abandoning".DumpString(); } break; // Give up } } } if (cancellor.IsCancellationRequested) { "W: interrupt received, killing client...\n".DumpString(); } request.Dispose(); return(null); }
public static void Interrupt(string[] args) { // // Interrupt // // Author: metadings // if (args == null || args.Length == 0) { args = new string[] { "World" }; } string name = args[0]; var error = default(ZError); using (var context = new ZContext()) using (var responder = new ZSocket(context, ZSocketType.REP)) { Console.CancelKeyPress += (s, ea) => { ea.Cancel = true; context.Shutdown(); }; responder.Bind("tcp://*:5555"); ZFrame request; while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo info = Console.ReadKey(true); /* if (info.Modifiers == ConsoleModifiers.Control && info.Key == ConsoleKey.C) * { * context.Shutdown(); * } /**/ if (info.Key == ConsoleKey.Escape) { context.Shutdown(); } } if (null == (request = responder.ReceiveFrame(ZSocketFlags.DontWait, out error))) { if (error == ZError.EAGAIN) { Thread.Sleep(1); continue; } if (error == ZError.ETERM) { break; // Interrupted } throw new ZException(error); } using (request) { Console.Write("Received: {0}!", request.ReadString()); Thread.Sleep(512); // See also the much slower reaction Console.WriteLine(" Sending {0}... ", name); if (!responder.Send(new ZFrame(name), out error)) { if (error == ZError.ETERM) { break; // Interrupted } throw new ZException(error); } } } if (error == ZError.ETERM) { Console.WriteLine("Terminated! You have pressed CTRL+C or ESC."); return; } throw new ZException(error); } }
// .split recv method // This is the {{recv}} method; it's a little misnamed because it first sends // any reply and then waits for a new request. If you have a better name // for this, let me know. // Send reply, if any, to broker and wait for next request. public ZMessage Recv(ZMessage reply, CancellationTokenSource cancellor) { if (reply == null && _expectReply) { throw new InvalidOperationException(); } if (reply != null) { if (_replyTo == null) { throw new InvalidOperationException(); } reply.Wrap(_replyTo); SendToBroker(MdpCommon.MdpwCmd.REPLY.ToHexString(), string.Empty, reply); } _expectReply = true; while (true) { if (cancellor.IsCancellationRequested || (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) { _context.Shutdown(); } var p = ZPollItem.CreateReceiver(); ZMessage msg; ZError error; if (Worker.PollIn(p, out msg, out error, Heartbeat)) { using (msg) { // If we got a reply if (Verbose) { msg.DumpZmsg("I: received message from broker:"); } Liveness = MdpCommon.HEARTBEAT_LIVENESS; // Don't try to handle errors, just assert noisily if (msg.Count < 3) { throw new InvalidOperationException(); } using (ZFrame empty = msg.Pop()) { if (!empty.ToString().Equals("")) { throw new InvalidOperationException(); } } using (ZFrame header = msg.Pop()) { if (!header.ToString().Equals(MdpCommon.MDPW_WORKER)) { throw new InvalidOperationException(); } } //header.ReadString().Equals(MDPW_WORKER); using (ZFrame command = msg.Pop()) { if (command.StrHexEq(MdpCommon.MdpwCmd.REQUEST)) { // We should pop and save as many addresses as there are // up to a null part, but for now, just save one... _replyTo = msg.Unwrap(); // .split process message // Here is where we actually have a message to process; we // return it to the caller application: return(msg.Duplicate()); } else if (command.StrHexEq(MdpCommon.MdpwCmd.HEARTBEAT)) { // Do nothing for heartbeats } else if (command.StrHexEq(MdpCommon.MdpwCmd.DISCONNECT)) { ConnectToBroker(); } else { "E: invalid input message: '{0}'".DumpString(command.ToString()); } } } } else if (Equals(error, ZError.ETERM)) { cancellor.Cancel(); break; // Interrupted } else if (Equals(error, ZError.EAGAIN) && --Liveness == 0) { if (Verbose) { "W: disconnected from broker - retrying...".DumpString(); } Thread.Sleep(Reconnect); ConnectToBroker(); } // Send HEARTBEAT if it's time if (DateTime.UtcNow > HeartbeatAt) { SendToBroker(MdpCommon.MdpwCmd.HEARTBEAT.ToHexString(), null, null); HeartbeatAt = DateTime.UtcNow + Heartbeat; } } if (cancellor.IsCancellationRequested) { "W: interrupt received, killing worker...\n".DumpString(); } return(null); }
private void UpdateLoop(object sender, DoWorkEventArgs e) { loopActive = true; int loopInterval = 50; // Loop to get and assign elements, then update UI while (loopActive) { AsyncFormUpdate(new Action(() => { lblStatus.Text = "Update Loop Running"; })); // Check to see if thread cancellation is pending // If true, stop the loop if (bwUpdateLoop.CancellationPending) { requester.Close(); context.Shutdown(); context.Dispose(); requester.Dispose(); loopActive = false; AsyncFormUpdate(new Action(() => { lblStatus.Text = "Update Loop Stopped"; })); break; } /// Socket Code // Send requester.Send(new ZFrame(_autoMode)); try { // Receive using (ZFrame reply = requester.ReceiveFrame()) { returnedData = JObject.Parse(reply.ToString()); } } catch (ZException ex) { requester.Close(); context.Shutdown(); context.Dispose(); requester.Dispose(); loopActive = false; AsyncFormUpdate(new Action(() => { lblMode.Text = "Loop Stopped"; lblStatus.Text = "Update Loop Stopped"; })); break; } // ====================================================== // Take all elements from the Dictionary and update the UI with them AsyncFormUpdate(new Action(() => ShowUI(returnedData))); // Stall the thread for a given interval to save on bandwidth Thread.Sleep(loopInterval); } /// update the UI with this status AsyncFormUpdate(new Action(() => { lblMode.Text = "Not Connected"; })); }
// Titanic service // Implements server side of http://rfc.zeromq.org/spec:9 public static void Titanic(string[] args) { bool verbosedeep = (args.Any(e => e.ToLower().Equals("-vd") || e.ToLower().Equals("--verbosedeep"))); bool verbose = verbosedeep || (args.Any(e => e.ToLower().Equals("-v") || e.ToLower().Equals("--verbose"))); Console.WriteLine("Verbose: {0}", verbose); Console.WriteLine("Verbosedeep: {0}", verbosedeep); CancellationTokenSource cancellor = new CancellationTokenSource(); Console.CancelKeyPress += (s, ea) => { ea.Cancel = true; cancellor.Cancel(); }; ZContext ctx = new ZContext(); using (var requestPipe = new ZActor(ctx, Titanic_Request, verbosedeep)) { (new Thread(() => Titanic_Reply(ctx, cancellor, verbosedeep))).Start(); (new Thread(() => Titanic_Close(ctx, cancellor, verbosedeep))).Start(); //////////////////// /// HINT: Use requestPipe.Start instead of requestPipe.Start(cancellor) /// => with cancellor consturctor needed frontent pipe will not be initializes!! //////////////////// requestPipe.Start(); Thread.Sleep(1500); // Main dispatcher loop while (true) { //continue; if (cancellor.IsCancellationRequested || (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) { ctx.Shutdown(); } var path = Path.Combine(TitanicCommon.TITANIC_DIR, TitanicCommon.QUEUE_FILE); var p = ZPollItem.CreateReceiver(); ZMessage msg; ZError error; if (requestPipe.Frontend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1000))) { using (msg) { // Ensure message directory exists Directory.CreateDirectory(TitanicCommon.TITANIC_DIR); // Append UUID to queue, prefixed with '-' for pending var uuid = Guid.Parse(msg.PopString()); using (var sw = File.AppendText(path)) { sw.Write(TitanicCommon.QUEUE_LINEFORMAT, uuid); } } } else if (error.Equals(ZError.ETERM)) { cancellor.Cancel(); break; // Interrupted } else if (error.Equals(ZError.EAGAIN)) //continue; { Thread.Sleep(1); } else { break; // Interrupted } // Brute force dispatcher if (File.Exists(path)) { using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { int numBytesRead = 0; int numBytesToRead = (new UTF8Encoding().GetBytes(String.Format(TitanicCommon.QUEUE_LINEFORMAT, Guid.NewGuid()))).Length; byte[] readBytes = new byte[numBytesToRead]; while (numBytesToRead > 0) { var n = fs.Read(readBytes, 0, numBytesToRead); if (n == 0) { break; } var line = (new UTF8Encoding()).GetString(readBytes, 0, n); // UUID is prefixed with '-' if still waiting if (line.StartsWith("-")) { var uuid = Guid.Parse(line.Substring(1, Guid.NewGuid().ToString().Length)); if (verbose) { "I: processing request {0}".DumpString(uuid); } if (Titanic_ServiceSuccess(uuid, cancellor)) { // Mark queue entry as processed var newval = (new UTF8Encoding()).GetBytes("+"); fs.Seek(-n, SeekOrigin.Current); fs.Write(newval, 0, newval.Length); fs.Seek(n - newval.Length, SeekOrigin.Current); } } if (cancellor.IsCancellationRequested) { break; } numBytesRead += n; numBytesToRead = n; } } } } } }