Beispiel #1
0
		static void AsyncSrv_ServerTask(ZContext context) 
		{
			// This is our server task.
			// It uses the multithreaded server model to deal requests out to a pool
			// of workers and route replies back to clients. One worker can handle
			// one request at a time but one client can talk to multiple workers at
			// once.

			using (var frontend = new ZSocket(context, ZSocketType.ROUTER))
			using (var backend = new ZSocket(context, ZSocketType.DEALER))
			{
				// Frontend socket talks to clients over TCP
				frontend.Bind("tcp://*:5570");
				// Backend socket talks to workers over inproc
				backend.Bind("inproc://backend");

				// Launch pool of worker threads, precise number is not critical
				for (int i = 0; i < 5; ++i)
				{
					int j = i; new Thread(() => AsyncSrv_ServerWorker(context, j)).Start();
				}

				// Connect backend to frontend via a proxy
				ZError error;
				if (!ZContext.Proxy(frontend, backend, out error))
				{
					if (error == ZError.ETERM)
						return;	// Interrupted
					throw new ZException(error);
				}
			}
		}
Beispiel #2
0
        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();
                }
            }
        }
Beispiel #3
0
		// 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());
				}
			}
		}
Beispiel #4
0
		static ZFrame FLClient1_TryRequest(ZContext context, string endpoint, ZFrame request)
		{
			Console.WriteLine("I: trying echo service at {0}...", endpoint);

			using (var client = new ZSocket(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;
		}
Beispiel #5
0
		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);
					}
				}
			}
		}
Beispiel #6
0
        //  Round-trip demonstrator
        //  While this example runs in a single process, that is just to make
        //  it easier to start and stop the example. The client task signals to
        //  main when it's ready.
        public static void Tripping(string[] args)
        {
            bool verbose = (args.Any(e => e.ToLower().Equals("-v")
                                          || e.ToLower().Equals("--verbose")));
            Console.WriteLine("Verbose: {0}", verbose);

            CancellationTokenSource cancellor = new CancellationTokenSource();
            Console.CancelKeyPress += (s, ea) =>
            {
                ea.Cancel = true;
                cancellor.Cancel();
            };

            using (ZContext ctx = new ZContext())
            {
                using (var client = new ZActor(ctx, Tripping_ClientTask))
                {
                    (new Thread(() => Tripping_WorkerTask(ctx))).Start();
                    (new Thread(() => Tripping_BrokerTask(ctx))).Start();
                    client.Start();
                    using (var signal = client.Frontend.ReceiveFrame())
                        if (verbose)
                            signal.ToString().DumpString();
                }
            }
        }
Beispiel #7
0
        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
                }
            }
        }
        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
                }
            }
        }
Beispiel #9
0
		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);
			}
		}
Beispiel #10
0
		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);
			}
		}
Beispiel #11
0
        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));
                    }
                }
            }
        }
Beispiel #12
0
		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);
				}
			}
		}
Beispiel #13
0
		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);
			}
		}
Beispiel #14
0
        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);
            }
        }
Beispiel #15
0
        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);
                }
            }
        }
Beispiel #16
0
        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);
                }
            }
        }
Beispiel #17
0
		public ZActor(ZContext context, ZAction action, params object[] args)
			: this(context, default(string), action, args)
		{
			var rnd0 = new byte[8];
			using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetNonZeroBytes(rnd0);
			this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
		}
Beispiel #18
0
        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);
                }
            }
        }
Beispiel #19
0
		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());
					}
				}
			}
		}
Beispiel #20
0
		// 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);
			}
		}
Beispiel #21
0
			public FreelanceClient()
			{
				// Constructor
				this.context = new ZContext();

				this.Actor = new ZActor(this.context, FreelanceClient.Agent);
				this.Actor.Start();
			}
Beispiel #22
0
			public FLClient() 
			{
				// Constructor

				context = new ZContext();
				socket = new ZSocket(context, ZSocketType.DEALER);
				socket.Linger = GLOBAL_TIMEOUT;
			}
Beispiel #23
0
		public ZActor(ZContext context, string endpoint, ZAction action, params object[] args)
			: base()
		{
			this.Context = context;

			this.Endpoint = endpoint;
			this.Action = action;
			this.Arguments = args;
		}
Beispiel #24
0
        /// <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);
        }
Beispiel #25
0
		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);
				}
			}
		}
Beispiel #26
0
		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);
						}
					}
				}
			}
		}
Beispiel #27
0
            //  The constructor and destructor are the same as in mdcliapi, except
            //  we don't do retries, so there's no retries property.
            //  .skip
            //  ---------------------------------------------------------------------
            public MajordomoClient(string broker, bool verbose)
            {
                if(broker == null)
                    throw new InvalidOperationException();
                _context = new ZContext();
                Broker = broker;
                Verbose = verbose;
                Timeout = TimeSpan.FromMilliseconds(2500);

                ConnectToBroker();
            }
Beispiel #28
0
        private NetMqManager()
        {
            //Poller.PollTillCancelledNonBlocking();

            Context = new ZContext();

            //Context.SetOption(ZContextOption.IO_THREADS, 1);

            //Context.MaxSockets = 10240;
            //Context.ThreadPoolSize = 128;
        }
Beispiel #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ZDevice"/> class.
        /// </summary>
        /// <param name="frontendSocket">
        /// A <see cref="ZSocket"/> that will pass incoming messages to <paramref name="backendSocket"/>.
        /// </param>
        /// <param name="backendSocket">
        /// A <see cref="ZSocket"/> that will receive messages from (and optionally send replies to) <paramref name="frontendSocket"/>.
        /// </param>
        /// <param name="mode">The <see cref="DeviceMode"/> for the current device.</param>
        protected ZDevice(ZContext context, ZSocketType frontendType, ZSocketType backendType)
            : base()
        {
            Context = context;

            ZError error;
            if (!Initialize(frontendType, backendType, out error))
            {
                throw new ZException(error);
            }
        }
Beispiel #30
0
		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"));
			}
		}
Beispiel #31
0
 public ZeroMQConnection(ZeroMQ.ZContext ctx = null)
 {
     _context = ctx ?? new ZeroMQ.ZContext();
     _socket  = new ZSocket(_context, ZSocketType.REP);
 }
Beispiel #32
0
        public MainWindow()
        {
            InitializeComponent();

            DateTime now = DateTime.Now;

            // Set the icon
            Uri iconUri = new Uri("logo1.ico", UriKind.RelativeOrAbsolute);

            this.Icon = BitmapFrame.Create(iconUri);

            // Warn about the liability
            Liability liab = new Liability();

            liab.Icon = BitmapFrame.Create(iconUri);
            liab.ShowDialog();

            if (!liab.continue_pressed)
            {
                this.Close();
                return;
            }

            BitmapImage src = new BitmapImage();

            src.BeginInit();
            src.UriSource   = new Uri("logo1.png", UriKind.RelativeOrAbsolute);
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.EndInit();

            logoLabel.Source = src;

            // First make the user chooose a webcam
            OpenFaceOffline.CameraSelection cam_select = new OpenFaceOffline.CameraSelection();
            cam_select.Icon = BitmapFrame.Create(iconUri);

            if (!cam_select.no_cameras_found)
            {
                cam_select.ShowDialog();
            }

            if (cam_select.camera_selected)
            {
                // Create the capture device
                int cam_id = cam_select.selected_camera.Item1;
                img_width  = cam_select.selected_camera.Item2;
                img_height = cam_select.selected_camera.Item3;

                UtilitiesOF.SequenceReader reader = new UtilitiesOF.SequenceReader(cam_id, img_width, img_height);

                if (reader.IsOpened())
                {
                    // Create the ZeroMQ context for broadcasting the results
                    zero_mq_context = ZeroMQ.ZContext.Create();
                    zero_mq_socket  = new ZSocket(zero_mq_context, ZeroMQ.ZSocketType.PUB);

                    // Bind on localhost port 5000
                    zero_mq_socket.Bind("tcp://127.0.0.1:5000");

                    processing_thread      = new Thread(() => VideoLoop(reader));
                    processing_thread.Name = "Webcam processing";
                    processing_thread.Start();
                }
                else
                {
                    string           messageBoxText = "Failed to open a webcam";
                    string           caption        = "Webcam failure";
                    MessageBoxButton button         = MessageBoxButton.OK;
                    MessageBoxImage  icon           = MessageBoxImage.Warning;

                    // Display message box
                    MessageBox.Show(messageBoxText, caption, button, icon);
                    this.Close();
                }

                // Create an overlay image for display purposes
                webcam_img = new OpenFaceOffline.OverlayImage();

                webcam_img.SetValue(Grid.RowProperty, 1);
                webcam_img.SetValue(Grid.ColumnProperty, 1);
                MainGrid.Children.Add(webcam_img);

                StartExperiment();
            }
            else
            {
                cam_select.Close();
                this.Close();
            }
        }