Start() 개인적인 메소드

private Start ( ) : void
리턴 void
예제 #1
0
 public void Start()
 {
     if (_queue != null && _poller != null)
     {
         this.Log().Info("启动ZeroMq队列服务");
         _queue.Start();
         _poller.Start();
     }
 }
예제 #2
0
        public void Receive_BrokerDisconnectedWithLogging_ShouldReturnRequest()
        {
            const string host_address    = "tcp://localhost:5555";
            var          loggingMessages = new List <string> ();

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new NetMQ.Poller())
                        using (var session = new MDPWorker(host_address, "test"))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors but don't answer
                            broker.ReceiveReady += (s, e) => e.Socket.ReceiveMessage();

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            // speed up the test
                            session.HeartbeatDelay = TimeSpan.FromMilliseconds(250);
                            session.ReconnectDelay = TimeSpan.FromMilliseconds(250);
                            // set the event handler to receive the logging messages
                            session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                            // initialize the worker - broker protocol
                            session.Receive(null);

                            poller.Stop();
                            poller.RemoveSocket(broker);

                            Assert.That(loggingMessages.Count(m => m.Contains("retrying")), Is.EqualTo(3));
                            // 3 times retrying and 1 time initial connecting
                            Assert.That(loggingMessages.Count(m => m.Contains("localhost")), Is.EqualTo(4));
                            Assert.That(loggingMessages.Last().Contains("abandoning"));
                        }
        }
            public void RunPipeline(PairSocket shim)
            {
                publisherSocket = context.CreatePublisherSocket();
                publisherSocket.Bind("tcp://*:" + StreamingProtocol.Port);

                snapshotSocket = context.CreateResponseSocket();
                snapshotSocket.Bind("tcp://*:" + SnapshotProtocol.Port);
                snapshotSocket.ReceiveReady += OnSnapshotReady;

                shim.ReceiveReady += OnShimReady;

                heartbeatTimer          = new NetMQTimer(StreamingProtocol.HeartbeatInterval);
                heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;

                shim.SignalOK();

                poller = new Poller();
                poller.AddSocket(shim);
                poller.AddSocket(snapshotSocket);
                poller.AddTimer(heartbeatTimer);
                poller.Start();

                publisherSocket.Dispose();
                snapshotSocket.Dispose();
            }
예제 #4
0
        static void Main(string[] args)
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (WSRouter router = context.CreateWSRouter())
                using (WSPublisher publisher = context.CreateWSPublisher())
                {
                    router.Bind("ws://localhost:80");                    
                    publisher.Bind("ws://localhost:81");

                    router.ReceiveReady += (sender, eventArgs) =>
                    {
                        string identity = router.ReceiveString();
                        string message = router.ReceiveString();

                        router.SendMore(identity).Send("OK");

                        publisher.SendMore("chat").Send(message);
                    };
                        
                    Poller poller = new Poller();
                    poller.AddSocket(router);

                    // we must add the publisher to the poller although we are not registering to any event.
                    // The internal stream socket handle connections and subscriptions and use the events internally
                    poller.AddSocket(publisher);
                    poller.Start();

                }
            }
        }
예제 #5
0
 private void PollerThread()
 {
     while (true)
     {
         try
         {
             if (poller == null || !poller.IsStarted)
             {
                 SignalService.Logger.Info("Start NetMQ Poller");
                 poller = new Poller();
                 poller.AddSocket(router);
                 poller.Start();
             }
         }
         catch (Exception e)
         {
             SignalService.Logger.Error("NetMQ Poller Thread Exception.\n{0}", e.StackTrace);
             if (poller != null)
             {
                 poller.Stop();
                 poller.Dispose();
             }
         }
     }
 }
예제 #6
0
        public void ReceiveImplicitConnect_ValidScenario_ShouldReturnRequest()
        {
            const string host_address    = "tcp://localhost:5557";
            var          loggingMessages = new List <string> ();

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new NetMQ.Poller())
                        using (var session = new MDPWorker(host_address, "test", new[] { (byte)'1' }))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                var msg = e.Socket.ReceiveMessage();
                                // we expect to receive a 5 Frame mesage
                                // [WORKER ADR][EMPTY]["MDPW01"]["READY"]["test"]
                                if (msg.FrameCount != 5)
                                {
                                    Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                                }
                                // make sure the frames are as expected
                                Assert.That(msg[1], Is.EqualTo(NetMQFrame.Empty));
                                Assert.That(msg[2].ConvertToString(), Is.EqualTo("MDPW01"));
                                Assert.That(msg[3].BufferSize, Is.EqualTo(1));
                                Assert.That(msg[3].Buffer[0], Is.EqualTo((byte)MDPCommand.Ready));
                                Assert.That(msg[4].ConvertToString(), Is.EqualTo("test"));

                                // tell worker to stop gracefully
                                var reply = new NetMQMessage();
                                reply.Push(new[] { (byte)MDPCommand.Kill });
                                // push MDP Version
                                reply.Push(msg[2]);
                                // push separator
                                reply.Push(NetMQFrame.Empty);
                                // push worker address
                                reply.Push(msg[0]);
                                // send reply which is a request for the worker
                                e.Socket.SendMessage(reply);
                            };

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            // set the event handler to receive the logging messages
                            session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                            // initialize the worker - broker protocol
                            session.Receive(null);

                            poller.Stop();
                            poller.RemoveSocket(broker);

                            Assert.That(loggingMessages.Count, Is.EqualTo(5));
                            Assert.That(loggingMessages[0], Is.EqualTo("[WORKER] connected to broker at tcp://localhost:5557"));
                            Assert.That(loggingMessages[1].Contains("[WORKER] sending"), Is.True);
                            Assert.That(loggingMessages[2].Contains("[WORKER] received"));
                            Assert.That(loggingMessages[4].Contains("abandoning"));
                        }
        }
예제 #7
0
        private static void Main(string[] args)
        {
            using (var ctx = NetMQContext.Create())
            {
                using (NetMQSocket frontend = ctx.CreateRouterSocket(), backend = ctx.CreateDealerSocket())
                {
                    frontend.Bind(FRONTEND_ENDPOINT);
                    backend.Bind(BACKEND_ENDPOINT);

                    //Handler for messages coming in to the frontend
                    frontend.ReceiveReady += (sender, e) =>
                        {
                            var msg = frontend.ReceiveMessage();
                            backend.SendMessage(msg); //Relay this message to the backend
                        };

                    //Handler for messages coming in to the backend
                    backend.ReceiveReady += (sender, e) =>
                        {
                            var msg = backend.ReceiveMessage();
                            frontend.SendMessage(msg); //Relay this message to the frontend
                        };

                    using (var poller = new Poller())
                    {
                        poller.AddSocket(backend);
                        poller.AddSocket(frontend);

                        //Listen out for events on both sockets and raise events when messages come in
                        poller.Start();
                    }
                }
            }
        }
예제 #8
0
        public void Receive_RequestWithWrongFirstFrame_ShouldThrowApplicationException()
        {
            const string host_address = "tcp://localhost:5555";

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new NetMQ.Poller())
                        using (var session = new MDPWorker(host_address, "test"))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                var msg = e.Socket.ReceiveMessage();
                                // we expect to receive a 5 Frame mesage
                                // [WORKER ADR][EMPTY]["MDPW01"]["READY"]["test"]
                                if (msg.FrameCount != 5)
                                {
                                    Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                                }
                                // make sure the frames are as expected
                                Assert.That(msg[1], Is.EqualTo(NetMQFrame.Empty));
                                Assert.That(msg[2].ConvertToString(), Is.EqualTo("MDPW01"));
                                Assert.That(msg[3].BufferSize, Is.EqualTo(1));
                                Assert.That(msg[3].Buffer[0], Is.EqualTo((byte)MDPCommand.Ready));
                                Assert.That(msg[4].ConvertToString(), Is.EqualTo("test"));

                                // tell worker to stop gracefully
                                var reply = new NetMQMessage();
                                reply.Push(new[] { (byte)MDPCommand.Kill });
                                // push MDP Version
                                reply.Push("MDPW01");
                                // push separator
                                reply.Push("Should be empty");
                                // push worker address
                                reply.Push(msg[0]);
                                // send reply which is a request for the worker
                                e.Socket.SendMessage(reply);
                            };

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            try
                            {
                                var reply = session.Receive(null);
                            }
                            catch (ApplicationException ex)
                            {
                                Assert.That(ex.Message, Is.EqualTo("First frame must be an empty frame!"));
                            }

                            poller.Stop();
                            poller.RemoveSocket(broker);
                        }
        }
		public void Start ()
		{
			ThrowIfDisposed ();
			nmqPoller = new Poller ();
			nmqClient = nmqContext.CreateRequestSocket ();
			nmqClient.Connect (Address.AbsoluteUri.TrimEnd ('/'));
			nmqScheduler = new NetMQScheduler (nmqContext, nmqPoller);
			Task.Factory.StartNew (() => nmqPoller.Start (), TaskCreationOptions.LongRunning);
		}
예제 #10
0
        public void Send_WrongHeaderFromBrokerNoLogging_ShouldThrowApplicationException()
        {
            const string host_address = "tcp://localhost:5555";

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new Poller())
                        using (var session = new MDPClient(host_address))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                // return empty reply
                                var msg = e.Socket.ReceiveMessage();
                                // we expect to receive a 4 Frame mesage
                                // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"]
                                if (msg.FrameCount != 5)
                                {
                                    Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                                }
                                // REQUEST socket will strip the his address + empty frame
                                // ROUTER has to add the address prelude in order to identify the correct socket(!)
                                // [REQ ADR][EMPTY]["MDPC00"]["echo"]["REQUEST"]
                                var clientAddress = msg.Pop();
                                msg.Pop(); // forget empty frame
                                var mdpVersion = msg.Pop();
                                msg.Pop(); // drop service name version
                                msg.Push("NoService");
                                msg.Push(mdpVersion);
                                msg.Push(NetMQFrame.Empty);
                                msg.Push(clientAddress); // reinsert the client's address

                                e.Socket.SendMessage(msg);
                            };

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            // well formed message
                            var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });

                            try
                            {
                                session.Send("echo", requestMessage);
                            }
                            catch (ApplicationException ex)
                            {
                                Assert.That(ex.Message, Is.EqualTo("[CLIENT INFO] answered by wrong service: NoService"));
                            }

                            poller.Stop();
                            poller.RemoveSocket(broker);
                        }
        }
예제 #11
0
        public void Send_CorrectInputWithLogging_ShouldReturnCorrectReply()
        {
            const string host_address    = "tcp://localhost:5555";
            var          loggingMessages = new List <string> ();

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new Poller())
                        using (var session = new MDPClient(host_address))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                var msg = e.Socket.ReceiveMessage();
                                // we expect to receive a 4 Frame mesage
                                // [client adrR][e][mdp header][service][request]
                                if (msg.FrameCount != 5)
                                {
                                    Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                                }
                                // REQUEST socket will strip the his address + empty frame
                                // ROUTER has to add the address prelude in order to identify the correct socket(!)
                                // [client adr][e][mdp header][service][reply]
                                var request = msg.Last.ConvertToString();                   // get the request string
                                msg.RemoveFrame(msg.Last);                                  // remove the request frame
                                msg.Append(new NetMQFrame(request + " OK"));                // append the reply frame
                                e.Socket.SendMessage(msg);
                            };

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            // set the event handler to receive the logging messages
                            session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                            // well formed message
                            var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                            // correct call
                            var reply = session.Send("echo", requestMessage);

                            poller.Stop();
                            poller.RemoveSocket(broker);

                            Assert.That(reply.FrameCount, Is.EqualTo(1));
                            Assert.That(reply.First.ConvertToString(), Is.EqualTo("REQUEST OK"));
                            Assert.That(loggingMessages.Count, Is.EqualTo(3));
                            Assert.That(loggingMessages[0], Is.EqualTo("[CLIENT] connecting to broker at tcp://localhost:5555"));
                            Assert.That(loggingMessages[1].Contains("[CLIENT INFO] sending"), Is.True);
                            Assert.That(loggingMessages[2].Contains("[CLIENT INFO] received"), Is.True);
                        }
        }
예제 #12
0
        public void Send_EmptyReplyFromBrokerWithLogging_ShouldThrowApplicationException()
        {
            const string host_address    = "tcp://localhost:5555";
            var          loggingMessages = new List <string> ();

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new Poller())
                        using (var session = new MDPClient(host_address))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                // return empty reply
                                var msg = e.Socket.ReceiveMessage();
                                // we expect to receive a 4 Frame mesage
                                // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"]
                                if (msg.FrameCount != 5)
                                {
                                    Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                                }
                                // REQUEST socket will strip the his address + empty frame
                                // ROUTER has to add the address prelude in order to identify the correct socket(!)
                                // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"]
                                e.Socket.SendMessage(msg);
                            };

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            // set the event handler to receive the logging messages
                            session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                            // well formed message
                            var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                            // correct call
                            session.Send("echo", requestMessage);

                            poller.Stop();
                            poller.RemoveSocket(broker);

                            Assert.That(loggingMessages.Count, Is.EqualTo(3));
                            Assert.That(loggingMessages[0], Is.EqualTo("[CLIENT] connecting to broker at tcp://localhost:5555"));
                            Assert.That(loggingMessages[1].Contains("[CLIENT INFO] sending"), Is.True);
                            Assert.That(loggingMessages[2].Contains("[CLIENT INFO] received"), Is.True);
                        }
        }
예제 #13
0
        public void Start()
        {
            using (m_serverSocket = m_context.CreateResponseSocket())
            {
                foreach (var address in m_addresses)
                {
                    m_log.InfoFormat("Listening on {0}", address);
                    m_serverSocket.Bind(address);
                }
                m_serverSocket.ReceiveReady += OnMessage;

                m_poller = new Poller();
                m_poller.AddSocket(m_serverSocket);

                m_poller.Start();
            }
        }
            public void RunPipeline(PairSocket shim)
            {
                // we should signal before running the poller but this will block the application
                shim.SignalOK();

                this.poller = new Poller();

                shim.ReceiveReady += OnShimReady;
                poller.AddSocket(shim);

                timeoutTimer          = new NetMQTimer(StreamingProtocol.Timeout);
                timeoutTimer.Elapsed += TimeoutElapsed;
                poller.AddTimer(timeoutTimer);

                Connect();

                poller.Start();

                if (subscriberSocket != null)
                {
                    subscriberSocket.Dispose();
                }
            }
예제 #15
0
        public void Send_WrongServiceNameWithLogging_ShouldLogPermanentError()
        {
            const string host_address    = "tcp://localhost:5555";
            var          loggingMessages = new List <string> ();

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new Poller())
                        using (var session = new MDPClient(host_address))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                // just swallow message -> wrong service name
                                var msg = e.Socket.ReceiveMessage();
                            };

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            // set the event handler to receive the logging messages
                            session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                            // well formed message
                            var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                            // wrong service name
                            session.Send("xyz", requestMessage);

                            poller.Stop();
                            poller.RemoveSocket(broker);

                            Assert.That(loggingMessages.Count, Is.EqualTo(7));
                            Assert.That(loggingMessages[6], Is.EqualTo("[CLIENT ERROR] permanent error, abandoning!"));
                        }
        }
예제 #16
0
            public void RunPipeline(Sockets.PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer          = new NetMQTimer(0);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable   = false;

                m_poller = new Poller();
                m_poller.AddSocket(m_pipe);
                m_poller.AddTimer(m_pingTimer);

                m_poller.Start();

                // the beacon might never been configured
                if (m_udpSocket != null)
                {
                    m_udpSocket.Dispose();
                }
            }
예제 #17
0
파일: Pipe.cs 프로젝트: yonglehou/Daytona
        public void Start(NetMQContext context)
        {
            this.SetUpMonitorChannel(context);
            this.SetUpAddSubscriberCountChannel(context);

            //this should work but the forwarder device appears to be broken - it does not use XSUb and XPUB sockets
            //forwarderDevice = new ForwarderDevice(context, PublishAddressServer, SubscribeAddressServer, DeviceMode.Threaded);
            //forwarderDevice.FrontendSetup.Subscribe(string.Empty);
            //forwarderDevice.Start();
            //while (!forwarderDevice.IsRunning)
            //{ }

            QueueDevce = new QueueDevice(context, PubSubControlBackAddressServer, PubSubControlFrontAddressServer, DeviceMode.Threaded);
            QueueDevce.Start();
            //while (!QueueDevce.IsRunning)
            //{
            //}

            this.Writeline("Control channel started");

            long count = 0;
            this.cancellationTokenSource = new CancellationTokenSource();
            var token = this.cancellationTokenSource.Token;
            Task.Run(() =>
            {
                using (frontend = context.CreateXSubscriberSocket())
                {
                    using (backend = context.CreateXPublisherSocket())
                    {
                        frontend.Bind(Pipe.PublishAddressServer); ////"tcp://*:5550");
                        backend.Bind(Pipe.SubscribeAddressServer); ////"tcp://*:5553");
                       // frontend.ReceiveReady += frontend_ReceiveReady;
                        frontend.ReceiveReady += new EventHandler<NetMQSocketEventArgs>(FrontendReceiveReady);
                        backend.ReceiveReady += new EventHandler<NetMQSocketEventArgs>(BackendReceiveReady);
                       // this.AddSubscriberCountChannel.ReceiveReady += new EventHandler<NetMQSocketEventArgs>(AddSubscriberCountChannelReceiveReady);
                        using (this.poller = new Poller(new NetMQSocket[] { frontend, backend, this.AddSubscriberCountChannel }))
                        {
                            Writeline("About to start polling");

                            while (true)
                            {
                                poller.Start(); // .PollOnce(); .Poll(new TimeSpan(0,0,0,0,5));
                                Writeline("polling" + count);
                                count++;
                                if (token.IsCancellationRequested)
                                {
                                    Writeline("break");
                                    break;
                                }
                            }
                        }

                        Writeline("stopped polling and exiting");
                    }
                }
            },
            token);
        }
예제 #18
0
        public void Receive_RequestWithWrongMDPComand_ShouldLogCorrectMessage()
        {
            const string host_address    = "tcp://localhost:5555";
            var          loggingMessages = new List <string> ();
            var          first           = true;

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new NetMQ.Poller())
                        using (var session = new MDPWorker(host_address, "test", Encoding.ASCII.GetBytes("Worker"), 2))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                var msg = e.Socket.ReceiveMessage();
                                // we expect to receive a 5 Frame mesage
                                // [WORKER ADR][EMPTY]["MDPW01"]["READY"]["test"]
                                if (msg.FrameCount != 5)
                                {
                                    return; // it is a HEARTBEAT
                                }
                                // make sure the frames are as expected
                                Assert.That(msg[1], Is.EqualTo(NetMQFrame.Empty));
                                Assert.That(msg[2].ConvertToString(), Is.EqualTo("MDPW01"));
                                Assert.That(msg[3].BufferSize, Is.EqualTo(1));
                                Assert.That(msg[3].Buffer[0], Is.EqualTo((byte)MDPCommand.Ready));
                                Assert.That(msg[4].ConvertToString(), Is.EqualTo("test"));

                                // tell worker to stop gracefully
                                var reply = new NetMQMessage();
                                if (first)
                                {
                                    reply.Push(new[] { (byte)0xff });
                                    first = false;
                                }
                                else
                                {
                                    reply.Push(new[] { (byte)MDPCommand.Kill });
                                }
                                // push MDP Version
                                reply.Push("MDPW01");
                                // push separator
                                reply.Push(NetMQFrame.Empty);
                                // push worker address
                                reply.Push(msg[0]);
                                // send reply which is a request for the worker
                                e.Socket.SendMessage(reply);
                            };
                            // set the event handler to receive the logging messages
                            session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            session.HeartbeatDelay = TimeSpan.FromMilliseconds(250);
                            session.ReconnectDelay = TimeSpan.FromMilliseconds(250);
                            // initialize the worker - broker protocol
                            session.Receive(null);

                            Assert.That(loggingMessages.Count(m => m.Contains("[WORKER ERROR] invalid command received")), Is.EqualTo(1));
                            Assert.That(loggingMessages.Count(m => m.Contains("abandoning")), Is.EqualTo(1));

                            poller.Stop();
                            poller.RemoveSocket(broker);
                        }
        }
예제 #19
0
        public void Receive_REPLYtoREQUEST_ShouldSendCorrectReply()
        {
            const string host_address    = "tcp://localhost:5557";
            var          loggingMessages = new List <string> ();

            // setup the counter socket for communication
            using (var ctx = NetMQContext.Create())
                using (var broker = ctx.CreateRouterSocket())
                    using (var poller = new NetMQ.Poller())
                        using (var session = new MDPWorker(host_address, "test", new[] { (byte)'W', (byte)'1' }))
                        {
                            broker.Bind(host_address);
                            // we need to pick up any message in order to avoid errors
                            broker.ReceiveReady += (s, e) =>
                            {
                                var msg = e.Socket.ReceiveMessage();
                                if (msg[3].Buffer[0] == (byte)MDPCommand.Ready)
                                {
                                    // this is a READY message and we
                                    // send REQUEST message
                                    var request = new NetMQMessage();
                                    request.Push("echo test");                        // [request]
                                    request.Push(NetMQFrame.Empty);                   // [e][request]
                                    request.Push("C1");                               // [client adr][e][request]
                                    request.Push(new[] { (byte)MDPCommand.Request }); // [command][client adr][e][request]
                                    request.Push(msg[2]);                             // [header][command][client adr][e][request]
                                    request.Push(NetMQFrame.Empty);                   // [e][header][command][client adr][e][request]
                                    request.Push(msg[0]);                             // [worker adr][e][header][command][client adr][e][request]
                                    // send reply which is a request for the worker
                                    e.Socket.SendMessage(request);
                                }

                                if (msg[3].Buffer[0] == (byte)MDPCommand.Reply)
                                {
                                    // we expect to receive
                                    // [WORKER ADR][e]["MDPW01"][REPLY][CLIENT ADR][e][request == "echo test"]
                                    // make sure the frames are as expected
                                    Assert.That(msg[0].ConvertToString(), Is.EqualTo("W1"));
                                    Assert.That(msg[1], Is.EqualTo(NetMQFrame.Empty));
                                    Assert.That(msg[2].ConvertToString(), Is.EqualTo("MDPW01"));
                                    Assert.That(msg[3].BufferSize, Is.EqualTo(1));
                                    Assert.That(msg[3].Buffer[0], Is.EqualTo((byte)MDPCommand.Reply));
                                    Assert.That(msg[4].ConvertToString(), Is.EqualTo("C1"));
                                    Assert.That(msg[5], Is.EqualTo(NetMQFrame.Empty));
                                    Assert.That(msg[6].ConvertToString(), Is.EqualTo("echo test"));

                                    // tell worker to stop gracefully
                                    var reply = new NetMQMessage();
                                    reply.Push(new[] { (byte)MDPCommand.Kill });
                                    // push MDP Version
                                    reply.Push(msg[2]);
                                    // push separator
                                    reply.Push(NetMQFrame.Empty);
                                    // push worker address
                                    reply.Push(msg[0]);
                                    // send reply which is a request for the worker
                                    e.Socket.SendMessage(reply);
                                }
                            };

                            poller.AddSocket(broker);
                            var t = Task.Factory.StartNew(() => poller.Start());

                            // set the event handler to receive the logging messages
                            session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                            // initialize the worker - broker protocol
                            // and get initial request
                            var workerRequest = session.Receive(null);
                            // just echo the request
                            session.Receive(workerRequest);

                            poller.Stop();
                            poller.RemoveSocket(broker);

                            Assert.That(loggingMessages.Count, Is.EqualTo(8));
                            Assert.That(loggingMessages[0], Is.EqualTo("[WORKER] connected to broker at tcp://localhost:5557"));
                            Assert.That(loggingMessages[1].Contains("Ready"));
                            Assert.That(loggingMessages[2].Contains("[WORKER] received"));
                            Assert.That(loggingMessages[3].Contains("Request"));
                            Assert.That(loggingMessages[4].Contains("Reply"));
                            Assert.That(loggingMessages[6].Contains("Kill"));
                            Assert.That(loggingMessages[7].Contains("abandoning"));
                        }
        }