Run() public method

Runs the poller on the caller's thread. Only returns when Stop or StopAsync are called from another thread.
public Run ( ) : void
return void
コード例 #1
0
ファイル: RequestReplyBroker.cs プロジェクト: cjkao/netmq
        private static void Main()
        {
            using (var frontend = new RouterSocket("@tcp://127.0.0.1:5559"))
            using (var backend = new DealerSocket("@tcp://127.0.0.1:5560"))
            {
                // Handler for messages coming in to the frontend
                frontend.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    backend.SendMultipartMessage(msg); // Relay this message to the backend
                };

                // Handler for messages coming in to the backend
                backend.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    frontend.SendMultipartMessage(msg); // Relay this message to the frontend
                };

                using (var poller = new NetMQPoller {backend, frontend})
                {
                    // Listen out for events on both sockets and raise events when messages come in
                    poller.Run();
                }
            }
        }
コード例 #2
0
ファイル: NetMQProactor.cs プロジェクト: cjkao/netmq
        private void Run(PairSocket shim)
        {
            shim.ReceiveReady += OnShimReady;
            m_receiveSocket.ReceiveReady += OnSocketReady;
            m_poller = new NetMQPoller { m_receiveSocket, shim };

            shim.SignalOK();
            m_poller.Run();

            m_receiveSocket.ReceiveReady -= OnSocketReady;
        }
コード例 #3
0
        public void ReceiveMessageFailedIfWasNotProcessed()
        {
            const string hostAddress = "tcp://localhost:5555";
            var loggingMessages = new List<string>();
            var serviceName = "echo";
            Guid requestId = Guid.Empty;

            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    // doesn't reply to client
                    var msg = e.Socket.ReceiveMultipartMessage();
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    Assert.IsTrue(false, "I'm not supposed to receive replies since broker is not sending them");
                    poller.Stop();
                };
                session.FailedRequest += (s, e) =>
                {
                    Assert.That(requestId, Is.Not.EqualTo(Guid.Empty));
                    Assert.That(e.RequestId, Is.EqualTo(requestId));
                    poller.Stop();
                };

                poller.Add(broker);
                var task = Task.Factory.StartNew(() => poller.Run());

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });

                requestId = session.Send(serviceName, requestMessage);
                var result = task.Wait(session.Timeout + session.Timeout);
                Assert.IsTrue(result, $"During {session.Timeout}ms was not received a FailedReply");
            }
        }
コード例 #4
0
ファイル: NetMQBeacon.cs プロジェクト: ohayo2003/netmq
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer          = new NetMQTimer(interval: TimeSpan.Zero);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable   = false;

                m_poller = new NetMQPoller {
                    m_pipe, m_pingTimer
                };

                m_poller.Run();

                // the beacon might never been configured
                m_udpSocket?.Close();
            }
コード例 #5
0
ファイル: NetMQBeacon.cs プロジェクト: sharpe5/netmq
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer = new NetMQTimer(interval: TimeSpan.Zero);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable = false;

                m_poller = new NetMQPoller { m_pipe, m_pingTimer };

                m_poller.Run();

                // the beacon might never been configured
                if (m_udpSocket != null)
                    m_udpSocket.Close();
            }
コード例 #6
0
ファイル: Bus.cs プロジェクト: vadian/netmq
        private void RunActor(PairSocket shim)
        {
            // save the shim to the class to use later
            m_shim = shim;

            // create all subscriber, publisher and beacon
            using (m_subscriber = new SubscriberSocket())
            using (m_publisher = new PublisherSocket())
            using (m_beacon = new NetMQBeacon())
            {
                // listen to actor commands
                m_shim.ReceiveReady += OnShimReady;

                // subscribe to all messages
                m_subscriber.Subscribe("");

                // we bind to a random port, we will later publish this port
                // using the beacon
                m_randomPort = m_subscriber.BindRandomPort("tcp://*");
                Console.WriteLine("Bus subscriber is bound to {0}", m_subscriber.Options.LastEndpoint);

                // listen to incoming messages from other publishers, forward them to the shim
                m_subscriber.ReceiveReady += OnSubscriberReady;

                // configure the beacon to listen on the broadcast port
                Console.WriteLine("Beacon is being configured to UDP port {0}", m_broadcastPort);
                m_beacon.Configure(m_broadcastPort);

                // publishing the random port to all other nodes
                Console.WriteLine("Beacon is publishing the Bus subscriber port {0}", m_randomPort);
                m_beacon.Publish(m_randomPort.ToString(), TimeSpan.FromSeconds(1));

                // Subscribe to all beacon on the port
                Console.WriteLine("Beacon is subscribing to all beacons on UDP port {0}", m_broadcastPort);
                m_beacon.Subscribe("");

                // listen to incoming beacons
                m_beacon.ReceiveReady += OnBeaconReady;

                // Create a timer to clear dead nodes
                NetMQTimer timer = new NetMQTimer(TimeSpan.FromSeconds(1));
                timer.Elapsed += ClearDeadNodes;

                // Create and configure the poller with all sockets and the timer
                m_poller = new NetMQPoller { m_shim, m_subscriber, m_beacon, timer };

                // signal the actor that we finished with configuration and
                // ready to work
                m_shim.SignalOK();

                // polling until cancelled
                m_poller.Run();
            }
        }
コード例 #7
0
ファイル: NetMQBeacon.cs プロジェクト: somdoron/netmq
            public void Run(PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer = new NetMQTimer(interval: TimeSpan.Zero);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable = false;

                using (m_poller = new NetMQPoller { m_pipe, m_pingTimer })
                {
                    m_poller.Run();
                }

                // the beacon might never been configured
                #if NET35
                m_udpSocket?.Close();
                #else
                m_udpSocket?.Dispose();
                #endif
            }
コード例 #8
0
        public void ReconnectToBrokerIfIsNotReplying()
        {
            const string hostAddress = "tcp://localhost:5555";
            const int timeOutToReconnectInMillis = 7500;
            var loggingMessages = new List<string>();
            var serviceName = "echo";
            var messagesReceivedOnBroker = 0;

            // setup the counter socket for communication
            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                session.Timeout = TimeSpan.FromMilliseconds(timeOutToReconnectInMillis);
                broker.Bind(hostAddress);
                broker.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    if (messagesReceivedOnBroker != 0) // doesn't respond if is the first message received!
                    {
                        // we expect to receive a 4 Frame message
                        // [client adrR][e][mdp header][service][request]
                        if (msg.FrameCount != 6)
                            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(!)

                        var requestId = msg.Last.ConvertToString(); // get the requestId string
                        msg.RemoveFrame(msg.Last); // remove the request frame

                        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
                        msg.Append(requestId);
                        e.Socket.SendMultipartMessage(msg);
                    }
                    messagesReceivedOnBroker++;
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    var reply = e.Reply;

                    Assert.That(reply.FrameCount, Is.EqualTo(1));
                    Assert.That(reply.First.ConvertToString(), Is.EqualTo("REQUEST OK"));

                    poller.Stop();
                };

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });

                int timeOutInMillis = timeOutToReconnectInMillis + 3000; // Waits for the timeOut on the client
                var timer = new NetMQTimer(timeOutInMillis);
                timer.Elapsed += (s, e) =>
                {
                    session.Send(serviceName, requestMessage); // resends the request after timeout
                };

                poller.Add(timer);
                poller.Add(broker);
                var task = Task.Factory.StartNew(() => poller.Run());

                session.Send(serviceName, requestMessage);

                var result = task.Wait(timeOutToReconnectInMillis * 2);

                var numberOfConnects = loggingMessages.FindAll(x => x.Contains("[CLIENT] connecting to broker")).Count;
                Assert.IsTrue(numberOfConnects > 1);
            }
        }
コード例 #9
0
        public void SendWrongMDPVersionFromBrokerNoLoggingShouldThrowApplicationException()
        {
            const string hostAddress = "tcp://localhost:5555";

            // setup the counter socket for communication
            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    // return empty reply
                    var msg = e.Socket.ReceiveMultipartMessage();
                    // we expect to receive a 4 Frame message
                    // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"][requestId]
                    if (msg.FrameCount != 6)
                        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"][requestId]
                    var clientAddress = msg.Pop();
                    msg.Pop(); // forget empty frame
                    msg.Pop(); // drop the MDP Version Frame
                    msg.Push("MDPC00"); // insert wrong MDP version
                    msg.Push(NetMQFrame.Empty);
                    msg.Push(clientAddress); // reinsert the client's address

                    e.Socket.SendMultipartMessage(msg);
                };

                int timeOutInMillis = 10000;
                var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong!
                timer.Elapsed += (s, e) =>
                {
                    Assert.Fail($"Waited {timeOutInMillis} and had no response from broker");
                    poller.Stop();
                };

                poller.Add(broker);
                poller.Add(timer);

                session.ReplyReady += (s, e) =>
                {
                    Assert.True(e.HasError());
                    Assert.That(e.Exception.Message, Is.StringContaining("MDP Version mismatch"));
                    poller.Stop(); // To unlock the Task.Wait()
                };

                session.FailedRequest += (s, e) =>
                {
                    Assert.True(e.HasError());
                    Assert.That(e.Exception.Message, Is.StringContaining("MDP Version mismatch"));
                    poller.Stop(); // To unlock the Task.Wait()
                };

                var task = Task.Factory.StartNew(() => poller.Run());

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                session.Send("echo", requestMessage);

                task.Wait();
            }
        }
コード例 #10
0
        public void SendEmptyReplyFromBrokerWithLoggingShouldThrowApplicationException()
        {
            const string hostAddress = "tcp://localhost:5555";
            var loggingMessages = new List<string>();

            // setup the counter socket for communication
            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    // return empty reply
                    var msg = e.Socket.ReceiveMultipartMessage();
                    // we expect to receive a 4 Frame message
                    // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"][requestId]
                    if (msg.FrameCount != 6)
                        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"][requestId]

                    e.Socket.SendMultipartMessage(msg);
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    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);

                    poller.Stop(); // To unlock the Task.Wait()
                };

                poller.Add(broker);
                var task = Task.Factory.StartNew(() => poller.Run());
                // well formed message
                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                // correct call
                session.Send("echo", requestMessage);

                int timeOutInMillis = 10000;
                var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong!
                timer.Elapsed += (s, e) =>
                {
                    Assert.Fail($"Waited {timeOutInMillis} and had no response from broker");
                    poller.Stop();
                };

                poller.Add(timer);
                task.Wait();
            }
        }
コード例 #11
0
        public void SendCorrectInputWithLoggingShouldReturnCorrectReply()
        {
            const string hostAddress = "tcp://localhost:5555";
            var loggingMessages = new List<string>();
            var serviceName = "echo";

            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    // we expect to receive a 4 Frame message
                    // [client adrR][e][mdp header][service][request]
                    if (msg.FrameCount != 6)
                        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][requestId]

                    var requestId = msg.Last.ConvertToString(); // get the requestId string
                    msg.RemoveFrame(msg.Last); // remove the request frame

                    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
                    msg.Append(requestId);
                    e.Socket.SendMultipartMessage(msg);
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    var reply = e.Reply;

                    Assert.That(reply.FrameCount, Is.EqualTo(1));
                    Assert.That(reply.First.ConvertToString(), Is.EqualTo("REQUEST OK"));

                    poller.Stop();
                };
                int timeOutInMillis = 10000;
                var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong!
                timer.Elapsed += (s, e) =>
                {
                    Assert.Fail($"Waited {timeOutInMillis} and had no response from broker");
                    poller.Stop();
                };

                poller.Add(broker);
                poller.Add(timer);
                var task = Task.Factory.StartNew(() => poller.Run());

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });

                session.Send(serviceName, requestMessage);

                task.Wait();

                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);
            }
        }