PollTillCancelled() 공개 메소드

Poll till Cancel or CancelAndJoin is called. This is a blocking method.
public PollTillCancelled ( ) : void
리턴 void
예제 #1
0
        public void Run(params string[] addresses)
        {
            using (m_context = NetMQContext.Create())
              {
            var subscriber = Connect(addresses);

            if (subscriber == null)
              throw new Exception("cannot connect to eny of the endpoints");

            // timeout timer, when heartbeat was not arrived for 5 seconds
            m_timeoutTimer = new NetMQTimer(TimeSpan.FromSeconds(5));
            m_timeoutTimer.Elapsed += (sender, args) =>
            {
              // timeout happend, first dispose existing subscriber
              subscriber.Dispose();
              m_poller.RemoveSocket(subscriber);

              // connect again
              subscriber = Connect(addresses);

              if (subscriber == null)
            throw new Exception("cannot connect to eny of the endpoints");

              m_poller.AddSocket(subscriber);
            };

            m_poller = new Poller(subscriber);
            m_poller.AddTimer(m_timeoutTimer);

            m_poller.PollTillCancelled();
              }
        }
예제 #2
0
        private static void Main()
        {
            using (var context = NetMQContext.Create())
            using (var frontend = context.CreateRouterSocket())
            using (var backend = context.CreateDealerSocket())
            {
                frontend.Bind(FrontendEndpoint);
                backend.Bind(BackendEndpoint);

                // 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.PollTillCancelled();
                }
            }
        }
예제 #3
0
        public static void Run()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (var publisherSocket = context.CreateXPublisherSocket())
                {
                    publisherSocket.SetWelcomeMessage("WM");
                    publisherSocket.Bind("tcp://*:6669");

                    // we just drop subscriptions
                    publisherSocket.ReceiveReady += (sender, eventArgs) => publisherSocket.SkipMultipartMessage();

                    Poller poller = new Poller(publisherSocket);

                    // send a message every second
                    NetMQTimer sendMessageTimer = new NetMQTimer(1000);
                    poller.AddTimer(sendMessageTimer);
                    sendMessageTimer.Elapsed +=
                        (sender, eventArgs) =>
                            publisherSocket.SendMoreFrame("A").SendFrame(new Random().Next().ToString());

                    // send heartbeat every two seconds
                    NetMQTimer heartbeatTimer = new NetMQTimer(2000);
                    poller.AddTimer(heartbeatTimer);
                    heartbeatTimer.Elapsed += (sender, eventArgs) => publisherSocket.SendFrame("HB");

                    poller.PollTillCancelled();
                }
            }
        }
예제 #4
0
        /// <summary>
        /// Start the proxy work, this will block until one of the sockets is closed
        /// </summary>
        public void Start()
        {
            m_frontend.ReceiveReady += OnFrontendReady;
            m_backend.ReceiveReady  += OnBackendReady;

            m_poller = new Poller(m_frontend, m_backend);
            m_poller.PollTillCancelled();
        }
예제 #5
0
파일: Chat.cs 프로젝트: torshy/DotNetZyre
        void IShimHandler.Run(PairSocket pipe)
        {
            _pipe = pipe;
            _pipe.SignalOK();
            _pipe.ReceiveReady += OnPipeReady;

            _zre = Zre.Create(_ctx, _name);
            _zre.ReceiveReady += OnZreReady;

            _poller = new Poller();
            _poller.AddSocket(_zre);
            _poller.AddSocket(_pipe);
            _poller.PollTillCancelled();
        }
예제 #6
0
        void IShimHandler.Run(PairSocket shim)
        {
            _pipe = shim;
            _pipe.SignalOK();
            _pipe.ReceiveReady += OnPipeReady;

            _timer = new NetMQTimer(TimeSpan.FromSeconds(1));
            _timer.Elapsed += OnPingPeer;

            _inbox = _context.CreateRouterSocket();
            _inbox.ReceiveReady += OnInboxReady;

            _poller = new Poller(_pipe);
            _poller.AddTimer(_timer);
            _poller.PollTillCancelled();
        }
예제 #7
0
파일: Program.cs 프로젝트: dshaneg/zmqpoc
        public static void Main(string[] args)
        {
            //
            // Task worker - design 2
            // Adds pub-sub flow to receive and respond to kill signal
            //
            // Author: metadings
            //

            // Socket to receive messages on,
            // Socket to send messages to and
            // Socket for control input
            using (var context = NetMQContext.Create())
            using (var receiver = context.CreatePullSocket())
            using (var sender = context.CreatePushSocket())
            using (var controller = context.CreateSubscriberSocket())
            {
                receiver.Connect("tcp://127.0.0.1:5557");
                sender.Connect("tcp://127.0.0.1:5558");
                controller.Connect("tcp://127.0.0.1:5559");

                controller.SubscribeToAnyTopic();

                var poller = new Poller();
                poller.AddSocket(receiver);
                poller.AddSocket(controller);

                receiver.ReceiveReady += (o, eventArgs) =>
                {
                    var workload = int.Parse(eventArgs.Socket.ReceiveFrameString());

                    Console.WriteLine("{0}.", workload); // Show progress

                    Thread.Sleep(workload); // Do the work

                    sender.SendFrame(new byte[0]); // Send results to sink
                };

                controller.ReceiveReady += (o, eventArgs) =>
                {
                    if (eventArgs.Socket.ReceiveFrameString() == "KILL");
                        poller.Cancel();
                };

                poller.PollTillCancelled();
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            {
                string[] topics = new string[] { "A", "B", "C" };
                Random random = new Random();

                using (var publisher = context.CreateXPublisherSocket())
                {
                    // Set publisher to manual subscriptions mode
                    publisher.Options.ManualPublisher = true;
                    publisher.Bind("tcp://*:5556");
                    publisher.ReceiveReady += (sender, eventArgs) =>
                    {
                        var message = publisher.ReceiveString();

                        // we only handle subscription requests, unsubscription and any
                        // other type of messages will be dropped
                        if (message[0] == (char)1)
                        {
                            // calling Subscribe to add subscription to the last subscriber
                            publisher.Subscribe(message.Substring(1));
                        }
                    };

                    NetMQTimer sendTimer = new NetMQTimer(1000);
                    sendTimer.Elapsed += (sender, eventArgs) =>
                    {
                        // sends a message every second with random topic and current time
                        publisher.
                            SendMore(topics[random.Next(3)]).
                            Send(DateTime.Now.ToString());
                    };

                    Poller poller = new Poller();
                    poller.AddSocket(publisher);
                    poller.AddTimer(sendTimer);
                    poller.PollTillCancelled();
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Start proxying messages between the front and back ends. Blocks, unless using an external <see cref="Poller"/>.
        /// </summary>
        /// <exception cref="InvalidOperationException">The proxy has already been started.</exception>
        public void Start()
        {
            if (Interlocked.CompareExchange(ref m_state, StateStarting, StateStopped) != StateStopped)
            {
                throw new InvalidOperationException("Proxy has already been started");
            }

            m_frontend.ReceiveReady += OnFrontendReady;
            m_backend.ReceiveReady  += OnBackendReady;

            if (m_externalPoller)
            {
                m_state = StateStarted;
            }
            else
            {
                m_poller = new Poller(m_frontend, m_backend);
                m_state  = StateStarted;
                m_poller.PollTillCancelled();
            }
        }
예제 #10
0
            public void Run(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.PollTillCancelled();

                // the beacon might never been configured
                if (m_udpSocket != null)
                {
                    m_udpSocket.Close();
                }
            }
예제 #11
0
        private void Run(PairSocket shim)
        {
            using (m_publisherSocket = m_context.CreateXPublisherSocket())
            {
                m_publisherSocket.SetWelcomeMessage(WelcomeMessage);
                m_publisherSocket.Bind(m_address);

                m_publisherSocket.ReceiveReady += DropPublisherSubscriptions;

                m_heartbeatTimer = new NetMQTimer(HeartbeatInterval);
                m_heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;

                shim.ReceiveReady += OnShimMessage;

                // signal the actor that the shim is ready to work
                shim.SignalOK();

                m_poller = new Poller(m_publisherSocket, shim);
                m_poller.AddTimer(m_heartbeatTimer);

                // Polling until poller is cancelled
                m_poller.PollTillCancelled();
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            // this key should be shared between authorization server and publisher
              const string Key = "SecretKey";

              string[] symbols = new[] {"EURUSD", "GBPUSD", "EURJPY",
            "USDJPY", "EURGBP", "GBPJPY"};

              Random random = new Random();

              using (var context = NetMQContext.Create())
              {
            using (var publisher = context.CreateXPublisherSocket())
            {
              publisher.Options.ManualPublisher = true;
              publisher.Bind("tcp://*:5558");
              publisher.ReceiveReady += (sender, eventArgs) =>
              {
            byte[] subscriptionBytes = publisher.Receive();

            if (subscriptionBytes[0] == 1 || subscriptionBytes[0] == 0)
            {
              // the rest of the bytes is the token, convert them to string
              string serializedToken = Encoding.ASCII.GetString(
                  subscriptionBytes, 1, subscriptionBytes.Length - 1);

              // deserialize the token
              Token token;

              if (Token.TryDeserialize(serializedToken, out token))
              {
                // Check if the token is valid
                if (token.Validate(Key))
                {
                  // first byte indicate if it a subscription or unsubscription
                  if (subscriptionBytes[0] == 1)
                  {
                    Console.WriteLine("Subscription request {0}",
                        token.Subscription);
                    publisher.Subscribe(token.Subscription);
                  }
                  else
                  {
                    publisher.Unsubscribe(token.Subscription);
                  }
                }
                else
                {
                  Console.WriteLine("Invalid token {0}",
                      serializedToken);
                }
              }
            }
              };

              // Some fake publishing
              NetMQTimer publishTimer = new NetMQTimer(100);
              publishTimer.Elapsed += (sender, eventArgs) =>
              {
            publisher.
                SendMore(symbols[random.Next(symbols.Length)]).
                Send(random.Next().ToString());
              };

              Poller poller = new Poller();
              poller.AddSocket(publisher);
              poller.AddTimer(publishTimer);
              poller.PollTillCancelled();
            }
              }
        }
예제 #13
0
        public void Listen(CancellationToken cancellationToken)
        {
            using (var electionServer = context.CreateResponseSocket())
            using (var leaderServer = context.CreateResponseSocket())
            using (var pingServer = context.CreateResponseSocket())
            using (var poller = new Poller())
            {
                electionServer.Bind(Settings.ElectionListenerEndpoint);
                leaderServer.Bind(Settings.LeaderListenerEndpoint);
                pingServer.Bind(Settings.PingListenerEndpoint);

                logger.Log($"ElectionListenerEndpoint: {Settings.ElectionListenerEndpoint}");
                logger.Log($"LeaderListenerEndpoint: {Settings.LeaderListenerEndpoint}");
                logger.Log($"PingListenerEndpoint: {Settings.PingListenerEndpoint}");

                poller.AddSocket(electionServer);
                poller.AddSocket(leaderServer);
                poller.AddSocket(pingServer);

                // Listen for new messages on the electionServer socket
                electionServer.ReceiveReady += (s, a) =>
                {
                    var msg = a.Socket.ReceiveFrameString();

                    logger.Log($"ELECTION MESSAGE: {msg}");
                    if (msg == Message.Election)
                    {
                        a.Socket.SendFrame(msg == Message.Election
                            ? Message.Ok
                            : Message.Fail);
                    }
                };

                // Listen for new messages on the leaderServer socket
                leaderServer.ReceiveReady += (s, a) =>
                {
                    var winnerMessage = a.Socket.ReceiveFrameString();
                    OnLeaderChanged(winnerMessage);
                    logger.Log($"NEW LEADER MESSAGE RECEIVED: {winnerMessage}");
                };

                // Listen for pings
                pingServer.ReceiveReady += (s, a) =>
                {
                    a.Socket.ReceiveFrameString();
                    a.Socket.SendFrame(Message.Ok);
                };

                logger.Log("-----------------------------------");

                poller.PollTillCancelled();
            }
        }
예제 #14
0
            public void Run(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.PollTillCancelled();

                // the beacon might never been configured
                if (m_udpSocket != null)
                {
                    m_udpSocket.Close();
                }
            }
예제 #15
0
        private void Connect()
        {
            List<SubscriberSocket> sockets = new List<SubscriberSocket>();
            Poller poller = new Poller();

            SubscriberSocket connectedSocket = null;

            // event handler to handle message from socket
            EventHandler<NetMQSocketEventArgs> handleMessage = (sender, args) =>
            {
                connectedSocket = (SubscriberSocket)args.Socket;
                poller.Cancel();
            };

            NetMQTimer timeoutTimer = new NetMQTimer(TimeOut);

            // just cancel the poller without seting the connected socket
            timeoutTimer.Elapsed += (sender, args) => poller.Cancel();
            poller.AddTimer(timeoutTimer);

            foreach (var address in m_addresses)
            {
                var socket = m_context.CreateSubscriberSocket();
                sockets.Add(socket);

                socket.ReceiveReady += handleMessage;
                poller.AddSocket(socket);

                // Subscribe to welcome message
                socket.Subscribe(WelcomeMessage);
                socket.Connect(address);
            }

            poller.PollTillCancelled();

            // if we a connected socket the connection attempt succeed
            if (connectedSocket != null)
            {
                // remove the connected socket form the list
                sockets.Remove(connectedSocket);

                // close all exsiting connections
                foreach (var socket in sockets)
                {
                    // to close them immediatly we set the linger to zero
                    socket.Options.Linger = TimeSpan.Zero;
                    socket.Dispose();
                }

                // set the socket
                m_subscriber = connectedSocket;

                // drop the welcome message
                m_subscriber.SkipMultipartMessage();

                // subscribe to heartbeat
                m_subscriber.Subscribe(HeartbeatMessage);

                // subscribe to all subscriptions
                foreach (string subscription in m_subscriptions)
                {
                    m_subscriber.Subscribe(subscription);
                }

                m_subscriber.ReceiveReady -= handleMessage;
                m_subscriber.ReceiveReady += OnSubscriberMessage;
                m_poller.AddSocket(m_subscriber);

                m_timeoutTimer.Enable = true;
                m_reconnectTimer.Enable = false;
            }
            else
            {
                // close all exsiting connections
                foreach (var socket in sockets)
                {
                    // to close them immediatly we set the linger to zero
                    socket.Options.Linger = TimeSpan.Zero;
                    socket.Dispose();
                }

                m_reconnectTimer.Enable = true;
                m_timeoutTimer.Enable = false;
            }
        }
예제 #16
0
        private void Run(PairSocket shim)
        {
            m_shim = shim;
            shim.ReceiveReady += OnShimMessage;

            m_timeoutTimer = new NetMQTimer(TimeOut);
            m_timeoutTimer.Elapsed += OnTimeoutTimer;

            m_reconnectTimer = new NetMQTimer(ReconnectTimer);
            m_reconnectTimer.Elapsed += OnReconnectTimer;

            m_poller = new Poller(shim);
            m_poller.AddTimer(m_timeoutTimer);
            m_poller.AddTimer(m_reconnectTimer);

            shim.SignalOK();

            Connect();

            m_poller.PollTillCancelled();

            if (m_subscriber != null)
                m_subscriber.Dispose();
        }
예제 #17
0
        private SubscriberSocket Connect(string[] addresses)
        {
            List<SubscriberSocket> sockets = new List<SubscriberSocket>();
              Poller poller = new Poller();

              SubscriberSocket connectedSocket = null;

              // event handler to handle message from socket
              EventHandler<NetMQSocketEventArgs> handleMessage = (sender, args) =>
              {
            if (connectedSocket == null)
            {
              connectedSocket = (SubscriberSocket) args.Socket;
              poller.Cancel();
            }
              };

              // If timeout elapsed just cancel the poller without seting the connected socket
              NetMQTimer timeoutTimer = new NetMQTimer(TimeSpan.FromSeconds(5));
              timeoutTimer.Elapsed += (sender, args) => poller.Cancel();
              poller.AddTimer(timeoutTimer);

              foreach (var address in addresses)
              {
            var socket = m_context.CreateSubscriberSocket();
            sockets.Add(socket);

            socket.ReceiveReady += handleMessage;
            poller.AddSocket(socket);

            // Subscribe to welcome message
            socket.Subscribe("WM");
            socket.Connect(address);
              }

              poller.PollTillCancelled();

              // if we a connected socket the connection attempt succeed
              if (connectedSocket != null)
              {
            // remove the connected socket form the list
            sockets.Remove(connectedSocket);

            // close all existing sockets
            CloseSockets(sockets);

            // drop the welcome message
            connectedSocket.SkipMultipartMessage();

            // subscribe to heartbeat
            connectedSocket.Subscribe("HB");

            // subscribe to our only topic
            connectedSocket.Subscribe("A");

            connectedSocket.ReceiveReady -= handleMessage;
            connectedSocket.ReceiveReady += OnSubscriberMessage;

            return connectedSocket;
              }
              else
              {
            // close all existing sockets
            CloseSockets(sockets);

            return null;
              }
        }
예제 #18
0
        /// <summary>
        /// Start proxying messages between the front and back ends. Blocks, unless using an external <see cref="Poller"/>.
        /// </summary>
        /// <exception cref="InvalidOperationException">The proxy has already been started.</exception>
        public void Start()
        {
            if (Interlocked.CompareExchange(ref m_state, StateStarting, StateStopped) != StateStopped)
            {
                throw new InvalidOperationException("Proxy has already been started");
            }

            m_frontend.ReceiveReady += OnFrontendReady;
            m_backend.ReceiveReady += OnBackendReady;

            if (m_externalPoller)
            {
                m_state = StateStarted;
            }
            else
            {
                m_poller = new Poller(m_frontend, m_backend);
                m_state = StateStarted;
                m_poller.PollTillCancelled();
            }
        }