示例#1
0
        public void MultipleSubscriptions()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("tcp://127.0.0.1:5002");

                    using (var sub = contex.CreateXSubscriberSocket())
                    {
                        sub.Connect("tcp://127.0.0.1:5002");
                        sub.Send(new byte[] { 1, (byte)'C' });
                        sub.Send(new byte[] { 1, (byte)'B' });
                        sub.Send(new byte[] { 1, (byte)'A' });
                        sub.Send(new byte[] { 1, (byte)'D' });
                        sub.Send(new byte[] { 1, (byte)'E' });

                        Thread.Sleep(500);

                        sub.Send(new byte[] { 0, (byte)'C' });
                        sub.Send(new byte[] { 0, (byte)'B' });
                        sub.Send(new byte[] { 0, (byte)'A' });
                        sub.Send(new byte[] { 0, (byte)'D' });
                        sub.Send(new byte[] { 0, (byte)'E' });

                        Thread.Sleep(500);
                    }
                }
            }
        }
示例#2
0
        public void Census()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("tcp://127.0.0.1:5002");

                    using (var sub = contex.CreateXSubscriberSocket())
                    {
                        sub.Options.ReceiveTimeout = TimeSpan.FromSeconds(2.0);

                        sub.Connect("tcp://127.0.0.1:5002");
                        sub.Send("Message from subscriber");

                        // let the subscriber connect to the publisher before sending a message
                        Thread.Sleep(500);

                        var txt = pub.ReceiveString();
                        Assert.AreEqual("Message from subscriber", txt);

                        sub.Send(new byte[] { });

                        var msg = pub.Receive();
                        Assert.True(msg.Length == 0);
                    }
                }
            }
        }
示例#3
0
        protected void CreateServer()
        {
            switch (_type)
            {
            case MQServerType.Response:
                _serverSocket = _context.CreateResponseSocket(); break;

            case MQServerType.Publisher:
                _serverSocket = _context.CreatePublisherSocket(); break;

            case MQServerType.Router:
                _serverSocket = _context.CreateRouterSocket(); break;

            case MQServerType.Stream:
                _serverSocket = _context.CreateStreamSocket(); break;

            case MQServerType.Push:
                _serverSocket = _context.CreatePushSocket(); break;

            case MQServerType.XPublisher:
                _serverSocket = _context.CreateXPublisherSocket(); break;

            default:
                _serverSocket = _context.CreateResponseSocket(); break;
            }

            _serverSocket.Bind("tcp://*:" + _port);
        }
示例#4
0
        public void Manual()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("inproc://manual");
                    pub.Options.ManualPublisher = true;

                    using (var sub = contex.CreateXSubscriberSocket())
                    {
                        sub.Connect("inproc://manual");

                        sub.Send(new byte[] { 1, (byte)'A' });
                        var subscription = pub.Receive();

                        Assert.AreEqual(subscription[1], (byte)'A');

                        pub.Subscribe("B");
                        pub.Send("A");
                        pub.Send("B");

                        var topic = sub.ReceiveString();

                        Assert.AreEqual("B", topic);
                    }
                }
            }
        }
示例#5
0
        public void WelcomeMessage()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("inproc://welcome");
                    pub.SetWelcomeMessage("W");

                    using (var sub = contex.CreateSubscriberSocket())
                    {
                        sub.Subscribe("W");
                        sub.Connect("inproc://welcome");

                        var subscription = pub.Receive();

                        Assert.AreEqual(subscription[1], (byte)'W');

                        var welcomeMessage = sub.ReceiveString();

                        Assert.AreEqual("W", welcomeMessage);
                    }
                }
            }
        }
示例#6
0
        void CreateServer()
        {
            switch (_type)
            {
            case ServerType.Response:
                _serverSocket = _context.CreateResponseSocket(); break;

            case ServerType.Pub:
                _serverSocket = _context.CreatePushSocket(); break;

            case ServerType.Router:
                _serverSocket = _context.CreateRouterSocket(); break;

            case ServerType.Stream:
                _serverSocket = _context.CreateStreamSocket(); break;

            case ServerType.Push:
                _serverSocket = _context.CreatePushSocket(); break;

            case ServerType.XPub:
                _serverSocket = _context.CreateXPublisherSocket(); break;

            default:
                _serverSocket = _context.CreateResponseSocket(); break;
            }
            _serverSocket.Bind("tcp://*:" + _port);
            Task.Factory.StartNew(() =>
                                  AsyncRead(_serverSocket), TaskCreationOptions.LongRunning);
        }
示例#7
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();
                }
            }
        }
示例#8
0
        public void SimplePubSub()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("tcp://127.0.0.1:5002");

                    using (var sub = contex.CreateXSubscriberSocket())
                    {
                        sub.Connect("tcp://127.0.0.1:5002");
                        sub.Send(new byte[] { 1 });

                        // let the subscriber connect to the publisher before sending a message
                        Thread.Sleep(500);

                        pub.Send("Hello");

                        bool more;

                        string m = sub.ReceiveString(out more);

                        Assert.AreEqual("Hello", m);
                        Assert.False(more);
                    }
                }
            }
        }
示例#9
0
        private void ProxyThread()
        {
            if (_disposeCount != 0)
            {
                _traces.Debug("IpcEventProxy: disposed before start.");
                return;
            }
            XSubscriberSocket xsub = null;
            XPublisherSocket  xpub = null;

            try
            {
                xsub = _context.CreateXSubscriberSocket();
                xpub = _context.CreateXPublisherSocket();

                xsub.Bind(_xSubscriberAddress);
                xpub.Bind(_xPublisherAddress);
                var xproxy = new Proxy(xpub, xsub, null);
                _traces.Debug("IpcEventProxy: started (pub->xsub {0} <=> {1} xpub<-sub)", _xSubscriberAddress, _xPublisherAddress);
                xproxy.Start();
                _traces.Debug("IpcEventProxy: stopped.");
            }
            catch (NetMQException ex)
            {
                if (_disposeCount == 0 && !(ex is TerminatingException))
                {
                    _isFaultedState = true;
                    _traces.Error(ex, "Error while IpcEventProxy starting or during operation.");
                    var handler = FaultedState;
                    if (handler != null)
                    {
                        try
                        {
                            handler(this, EventArgs.Empty);
                        }
                        catch (Exception ex2)
                        {
                            _traces.Error(ex2);
                        }
                    }
                }
            }
            finally
            {
                if (xsub != null)
                {
                    _traces.CaptureMqExceptions(xsub.Dispose);
                }
                if (xpub != null)
                {
                    _traces.CaptureMqExceptions(xpub.Dispose);
                }
            }
        }
示例#10
0
        public void UnSubscribe()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("tcp://127.0.0.1:5002");

                    using (var sub = contex.CreateXSubscriberSocket())
                    {
                        sub.Connect("tcp://127.0.0.1:5002");
                        sub.Send(new byte[] { 1, (byte)'A' });

                        // let the subscrbier connect to the publisher before sending a message
                        Thread.Sleep(500);

                        pub.SendMore("A");
                        pub.Send("Hello");

                        bool more;

                        string m = sub.ReceiveString(out more);

                        Assert.AreEqual("A", m);
                        Assert.IsTrue(more);

                        string m2 = sub.ReceiveString(out more);

                        Assert.AreEqual("Hello", m2);
                        Assert.False(more);

                        sub.Send(new byte[] { 0, (byte)'A' });

                        Thread.Sleep(500);

                        pub.SendMore("A");
                        pub.Send("Hello");

                        string m3 = sub.ReceiveString(true, out more);
                    }
                }
            }
        }
示例#11
0
        public void MultipleSubscribers()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("tcp://127.0.0.1:5002");

                    using (var sub = contex.CreateXSubscriberSocket())
                        using (var sub2 = contex.CreateXSubscriberSocket())
                        {
                            sub.Connect("tcp://127.0.0.1:5002");
                            sub.Send(new byte[] { 1, (byte)'A' });
                            sub.Send(new byte[] { 1, (byte)'A', (byte)'B' });
                            sub.Send(new byte[] { 1, (byte)'B' });
                            sub.Send(new byte[] { 1, (byte)'C' });

                            sub2.Connect("tcp://127.0.0.1:5002");
                            sub2.Send(new byte[] { 1, (byte)'A' });
                            sub2.Send(new byte[] { 1, (byte)'A', (byte)'B' });
                            sub2.Send(new byte[] { 1, (byte)'C' });

                            Thread.Sleep(500);

                            pub.SendMore("AB");
                            pub.Send("1");

                            string message = sub.ReceiveStringMessages().First();

                            Assert.AreEqual("AB", message, "First subscriber is expected to receive the message");

                            message = sub2.ReceiveStringMessages().First();

                            Assert.AreEqual("AB", message, "Second subscriber is expected to receive the message");
                        }
                }
            }
        }
示例#12
0
        public void NotSubscribed()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("tcp://127.0.0.1:5002");

                    using (var sub = contex.CreateXSubscriberSocket())
                    {
                        sub.Connect("tcp://127.0.0.1:5002");

                        // let the subscriber connect to the publisher before sending a message
                        Thread.Sleep(500);

                        pub.Send("Hello");

                        bool more;

                        string m = sub.ReceiveString(true, out more);
                    }
                }
            }
        }
示例#13
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();
            }
        }
示例#14
0
        public void MultiplePublishers()
        {
            using (NetMQContext contex = NetMQContext.Create()) {
                using (var pub = contex.CreateXPublisherSocket())
                    using (var pub2 = contex.CreateXPublisherSocket()) {
                        var address  = "tcp://127.0.0.1:5002";
                        var address2 = "tcp://127.0.0.1:5003";
                        pub.Bind(address);
                        pub2.Bind(address2);

                        // see comments below why verbose option is needed in this test
                        pub.Options.XPubVerbose  = true;
                        pub2.Options.XPubVerbose = true;

                        using (var sub = contex.CreateXSubscriberSocket())
                            using (var sub2 = contex.CreateXSubscriberSocket())
                            {
                                sub.Connect(address);
                                sub.Connect(address2);

                                sub2.Connect(address);
                                sub2.Connect(address2);

                                // should subscribe to both
                                sub.Send(new byte[] { 1, (byte)'A' });
                                sub2.Send(new byte[] { 1, (byte)'A' });

                                Thread.Sleep(500);

                                var msg = pub.ReceiveString();
                                Assert.AreEqual(2, msg.Length);
                                Assert.AreEqual(1, msg[0]);
                                Assert.AreEqual('A', msg[1]);

                                var msg2 = pub2.Receive();
                                Assert.AreEqual(2, msg2.Length);
                                Assert.AreEqual(1, msg2[0]);
                                Assert.AreEqual('A', msg2[1]);


                                // Next two blocks (pub(2).Receive) will hang without XPub verbose option:
                                // sub and sub2 both have sent `.Send(new byte[] { 1, (byte)'A' });` messages
                                // which are the same, so XPub will discard the second message for .Receive()
                                // because it is normally used to pass topics upstream.
                                // (un)subs are done in XPub.cs at line 150-175, quote:
                                // >> If the subscription is not a duplicate, store it so that it can be
                                // >> passed to used on next recv call.
                                // For verbose:
                                // >> If true, send all subscription messages upstream, not just unique ones

                                // These options must be set before sub2.Send(new byte[] { 1, (byte)'A' });
                                // pub.Options.XPubVerbose = true;
                                // pub2.Options.XPubVerbose = true;
                                // Note that resending sub2.Send(..) here wont help because XSub won't resent existing subs to XPub - quite sane behavior
                                // Comment out the verbose options and the next 8 lines and the test will
                                // still pass, even with non-unique messages from subscribers (see the bottom of the test)

                                msg = pub.ReceiveString();
                                Assert.AreEqual(2, msg.Length);
                                Assert.AreEqual(1, msg[0]);
                                Assert.AreEqual('A', msg[1]);

                                msg2 = pub2.Receive();
                                Assert.AreEqual(2, msg2.Length);
                                Assert.AreEqual(1, msg2[0]);
                                Assert.AreEqual('A', msg2[1]);


                                pub.SendMore("A");
                                pub.Send("Hello from the first publisher");

                                bool   more;
                                string m = sub.ReceiveString(out more);
                                Assert.AreEqual("A", m);
                                Assert.IsTrue(more);
                                string m2 = sub.ReceiveString(out more);
                                Assert.AreEqual("Hello from the first publisher", m2);
                                Assert.False(more);
                                // this returns the result of the latest
                                // connect - address2, not the source of the message
                                // This is documented here: http://api.zeromq.org/3-2:zmq-getsockopt
                                var ep = sub2.Options.GetLastEndpoint;
                                //Assert.AreEqual(address, ep);

                                // same for sub2
                                m = sub2.ReceiveString(out more);
                                Assert.AreEqual("A", m);
                                Assert.IsTrue(more);
                                m2 = sub2.ReceiveString(out more);
                                Assert.AreEqual("Hello from the first publisher", m2);
                                Assert.False(more);



                                pub2.SendMore("A");
                                pub2.Send("Hello from the second publisher");

                                string m3 = sub.ReceiveString(out more);

                                Assert.AreEqual("A", m3);
                                Assert.IsTrue(more);

                                string m4 = sub.ReceiveString(out more);

                                Assert.AreEqual("Hello from the second publisher", m4);
                                Assert.False(more);
                                ep = sub2.Options.GetLastEndpoint;
                                Assert.AreEqual(address2, ep);


                                // same for sub2
                                m3 = sub2.ReceiveString(out more);
                                Assert.AreEqual("A", m3);
                                Assert.IsTrue(more);
                                m4 = sub2.ReceiveString(out more);
                                Assert.AreEqual("Hello from the second publisher", m4);
                                Assert.False(more);

                                // send both to address and address2
                                sub.Send("Message from subscriber");
                                sub2.Send("Message from subscriber 2");

                                var txt = pub.ReceiveString();
                                Assert.AreEqual("Message from subscriber", txt);
                                var txt2 = pub2.ReceiveString();
                                Assert.AreEqual("Message from subscriber", txt2);

                                // Does not hang even though is the same as above, but the first byte is not 1 or 0.
                                // Won't hang even when messages are equal
                                txt = pub.ReceiveString();
                                Assert.AreEqual("Message from subscriber 2", txt);
                                txt2 = pub2.ReceiveString();
                                Assert.AreEqual("Message from subscriber 2", txt2);
                            }
                    }
            }
        }
        private void initServerThr()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (var receiver = context.CreateXSubscriberSocket())
                    using (var publisher = context.CreateXPublisherSocket())
                    {
                        try
                        {
                            receiver.Bind(cfg.ServerR);
                            publisher.Bind(cfg.ServerS);
                        }
                        catch (Exception ex)
                        {
                            DCLogger.LogError("Exception in ServerThr's bind work:{0}", ex.Message);
                        }

                        // send heartbeat every two seconds
                        poller = new Poller();
                        NetMQTimer heartbeatTimer = new NetMQTimer(10000);
                        poller.AddTimer(heartbeatTimer);
                        heartbeatTimer.Elapsed += (sender, eventArgs) =>
                        {
                            try
                            {
                                publisher.SendMultipartBytes(Global.DC_CTRL_HB, BitConverter.GetBytes(DateTime.Now.Ticks));
                                DCLogger.LogInfo("Server's HeartBeat sended:{0}", DateTime.Now);
                            }
                            catch (Exception ex)
                            {
                                DCLogger.LogError("Exception in ServerThr's heartbeat work:{0}", ex.Message);
                            }
                        };

                        poller.PollTillCancelledNonBlocking();

                        // proxy messages between frontend / backend
                        proxy = new Proxy(receiver, publisher);

                        // blocks indefinitely
                        proxy.Start();

                        ////r & s
                        //receiver.ReceiveReady += (sender, eventArgs) =>
                        //    {
                        //        try
                        //        {

                        //            List<byte[]> dataLst = new List<byte[]>();
                        //            receiver.ReceiveMultipartBytes(ref dataLst, 2);
                        //            DCLogger.LogInfo("Received:{0}", Global.Encoding.GetString(dataLst[0]));

                        //            if (dataLst.Count != 2)
                        //                return;

                        //            publisher.SendMultipartBytes(dataLst[0], dataLst[1]);
                        //            DCLogger.LogInfo("Sended:{0}", Global.Encoding.GetString(dataLst[0]));
                        //        }
                        //        catch (Exception ex)
                        //        {
                        //            DCLogger.LogError("Exception in ServerThr's exchange work:{0}", ex.Message);
                        //        }
                        //    };


                        //poller.AddSocket(receiver);
                    }
            }
        }
        private void initServerThr()
        {
            poller = new Poller();
            using (NetMQContext context = NetMQContext.Create())
            {
                //using (var receiver = context.CreatePullSocket())
                using (var publisher = context.CreateXPublisherSocket())
                {
                    try
                    {
                        //receiver.Bind(cfg.ServerR);
                        publisher.Bind(cfg.ServerS);
                    }
                    catch (Exception ex)
                    {
                        DCLogger.LogError("Exception in ServerThr's bind work:{0}", ex.Message);
                    }

                    //r & s
                    publisher.ReceiveReady += (sender, eventArgs) =>
                    {
                        try
                        {
                            List <byte[]> dataLst = new List <byte[]>();
                            publisher.ReceiveMultipartBytes(ref dataLst, 2);
                            DCLogger.LogInfo("Received:{0}", Global.Encoding.GetString(dataLst[0]));

                            if (dataLst.Count != 2)
                            {
                                return;
                            }

                            publisher.SendMultipartBytes(dataLst[0], dataLst[1]);
                            DCLogger.LogInfo("Sended:{0}", Global.Encoding.GetString(dataLst[0]));
                        }
                        catch (Exception ex)
                        {
                            DCLogger.LogError("Exception in ServerThr's exchange work:{0}", ex.Message);
                        }
                    };


                    poller.AddSocket(publisher);

                    // send heartbeat every two seconds
                    NetMQTimer heartbeatTimer = new NetMQTimer(10000);
                    poller.AddTimer(heartbeatTimer);
                    heartbeatTimer.Elapsed += (sender, eventArgs) =>
                    {
                        try
                        {
                            publisher.SendMultipartBytes(Global.DC_CTRL_HB, BitConverter.GetBytes(DateTime.Now.Ticks));
                            DCLogger.LogInfo("Server's HeartBeat sended:{0}", DateTime.Now);
                        }
                        catch (Exception ex)
                        {
                            DCLogger.LogError("Exception in ServerThr's heartbeat work:{0}", ex.Message);
                        }
                    };

                    poller.PollTillCancelled();
                }
            }
        }
示例#17
0
        public void Start()
        {
            using (NetMQSocket response_socket = context.CreateResponseSocket())
                using (NetMQSocket publisher_socket = context.CreateXPublisherSocket()) {
                    string response_address  = string.Format("tcp://{0}:{1}", Address, ResponsePort);
                    string publisher_address = string.Format("tcp://{0}:{1}", Address, PublisherPort);

                    response_socket.Bind(response_address);
                    publisher_socket.Bind(publisher_address);

                    Console.WriteLine("[response_socket] Bound on {0}", response_address);
                    Console.WriteLine("[publisher_socket] Bound on {0}", publisher_address);

                    using (Poller poller = new Poller(response_socket, publisher_socket)) {
                        response_socket.ReceiveReady += delegate(object sender, NetMQSocketEventArgs args) {
                            string message = response_socket.ReceiveString();

                            if (message.StartsWith("blow"))
                            {
                                string song  = "";
                                string notes = "";

                                try {
                                    song  = response_socket.ReceiveString();
                                    notes = response_socket.ReceiveString();

                                    if (song.Length > 64)
                                    {
                                        song = song.Substring(0, 64);
                                    }

                                    if (notes.Length > 64)
                                    {
                                        notes = notes.Substring(0, 64);
                                    }

                                    cache [song] = notes;

                                    Console.WriteLine("[response_socket] Received: song: {0}, notes: {1}", song, notes);
                                } catch (Exception e) {
                                    Console.WriteLine("[response_socket] Invalid request: {0}", e.Message);
                                }

                                response_socket.Send("OK");
                                Console.WriteLine("[response_socket] Sent: OK");

                                publisher_socket.SendMore(song).Send(notes);

                                Console.WriteLine("[publisher_socket] Sent: song: {0}, notes: {1}", song, notes);
                                return;
                            }

                            if (message.Equals("ping"))
                            {
                                Console.WriteLine("[response_socket] Received: {0}", message);

                                int timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                                response_socket.Send(timestamp.ToString());

                                Console.WriteLine("[response_socket] Sent: {0}", timestamp);
                                return;
                            }

                            Console.WriteLine("[response_socket] Invalid request: {0}", message);
                            args.Socket.Send("Meow?");
                        };

                        // Send cached notes to new subscribers
                        publisher_socket.ReceiveReady += delegate(object sender, NetMQSocketEventArgs args) {
                            NetMQMessage message = publisher_socket.ReceiveMessage();

                            // Subscribe == 1, Unsubscibe == 0
                            if (message.First.Buffer [0] != 1)
                            {
                                return;
                            }

                            string song         = message.First.ConvertToString().Substring(1);
                            string cached_notes = (string)cache [song];

                            if (cached_notes != null)
                            {
                                publisher_socket.SendMore(song).Send(cached_notes);
                            }
                        };

                        poller.Start();
                    }
                }
        }