Subscribe() public méthode

Subscribe this socket to the given 'topic' - which means enable this socket to receive messages that begin with this array of bytes.
public Subscribe ( byte topic ) : void
topic byte this specifies what byte-array prefix to subscribe to
Résultat void
    /* =====================
     * UNITY PLAYER EVENT HOOKS
     * =====================
     */

    // Function called when Unity Player is loaded.
    public IEnumerator Start()
    {
        // Check if the program should use CLI arguments (with defaults)
        if (!Application.isEditor)
        {
            pose_host  = GetArg("-pose-host", pose_host_default);
            video_host = GetArg("-video-host", video_host_default);
        }

        // Init simple splash screen
        Text text_obj = splashScreen.GetComponentInChildren <Text>(true);

        text_obj.text = "FlightGoggles Simulation Environment" + Environment.NewLine +
                        flight_goggles_version + Environment.NewLine + Environment.NewLine +
                        "Waiting for client connection..." + Environment.NewLine + Environment.NewLine +
                        "Pose input socket:" + Environment.NewLine + pose_host + Environment.NewLine + Environment.NewLine +
                        "Video output socket:" + Environment.NewLine + video_host;

        splashScreen.SetActive(true);

        // Fixes for Unity/NetMQ conflict stupidity.
        AsyncIO.ForceDotNet.Force();
        socket_lock = new object();

        // Connect sockets
        Debug.Log("Creating sockets.");
        pull_socket = new NetMQ.Sockets.SubscriberSocket();
        pull_socket.Options.ReceiveHighWatermark = 90;
        pull_socket.Connect(pose_host);

        // Setup subscriptions.
        pull_socket.Subscribe("Pose");
        push_socket = new NetMQ.Sockets.PublisherSocket();
        push_socket.Connect(video_host);
        Debug.Log("Sockets bound.");

        // Initialize Internal State
        internal_state = new UnityState_t();

        // Do not try to do any processing this frame so that we can render our splash screen.
        internal_state.screenSkipFrames = 1;

        // Wait until end of frame to transmit images
        while (true)
        {
            // Wait until all rendering + UI is done.
            // Blocks until the frame is rendered.
            yield return(new WaitForEndOfFrame());

            // Check if this frame should be rendered.
            if (internal_state.readyToRender)
            {
                // Read the frame from the GPU backbuffer and send it via ZMQ.
                sendFrameOnWire();
            }
        }
    }
    void InstantiateSockets()
    {
        // Configure sockets
        Debug.Log("Configuring sockets.");
        pull_socket = new NetMQ.Sockets.SubscriberSocket();
        pull_socket.Options.ReceiveHighWatermark = 90;

        // Setup subscriptions.
        pull_socket.Subscribe("Pose");
        push_socket = new NetMQ.Sockets.PublisherSocket();
        push_socket.Options.Linger = TimeSpan.Zero; // Do not keep unsent messages on hangup.
    }
Exemple #3
0
        public void MultipleSubscriptions()
        {
            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                var port = pub.BindRandomPort("tcp://127.0.0.1");
                sub.Connect("tcp://127.0.0.1:" + port);
                sub.Subscribe("C");
                sub.Subscribe("B");
                sub.Subscribe("A");
                sub.Subscribe("D");
                sub.Subscribe("E");

                Thread.Sleep(500);

                sub.Unsubscribe("C");
                sub.Unsubscribe("B");
                sub.Unsubscribe("A");
                sub.Unsubscribe("D");
                sub.Unsubscribe("E");

                Thread.Sleep(500);
            }
        }
Exemple #4
0
        public void ConnectBothSockets()
        {
            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                pub.Connect("pgm://224.0.0.1:5555");
                sub.Connect("pgm://224.0.0.1:5555");

                sub.Subscribe("");

                pub.SendFrame("Hi");

                bool more;
                Assert.AreEqual("Hi", sub.ReceiveFrameString(out more));
                Assert.IsFalse(more);
            }
        }
    public void init(string address, int port)
    {
        this.address = address;
        this.port    = port;

        //create context
        context = NetMQContext.Create();

        //create client
        client = context.CreateSubscriberSocket();
        //subscribe (must be before Connect!)
        client.Subscribe("");
        //connect client
        client.Connect("tcp://" + address + ":" + port);

        //add "getData" as callback
        client.ReceiveReady += getData;
    }
Exemple #6
0
    private void ReceiveInformation()
    {
        WWW    www   = new WWW(URL_RECV);
        string topic = room_id;

        using (var subSocket = new NetMQ.Sockets.SubscriberSocket())
        {
            subSocket.Options.ReceiveHighWatermark = 1000;
            subSocket.Connect(URL_RECV);
            subSocket.Subscribe(topic);
            //Console.WriteLine("Subscriber socket connecting...");

            while (true)
            {
                var messageTopicReceived = subSocket.ReceiveFrameString();
                var messageReceived      = subSocket.ReceiveFrameString();
                //Debug.Log(messageReceived);
                PlayerJson[] players = JsonHelper.FromJson <PlayerJson>(messageReceived);

                foreach (var playerData in players)
                {
                    bool found = false;
                    for (int i = 0; i < submarines.Count && !found; ++i)
                    {
                        if (submarines[i].GetId() == playerData.id)
                        {
                            submarines[i].SetPositionX(playerData.pos_x);
                            submarines[i].SetPositionY(playerData.pos_y);
                            found = true;
                        }
                    }
                    for (int i = 0; i < divers.Count && !found; ++i)
                    {
                        if (divers[i].GetId() == playerData.id)
                        {
                            divers[i].SetPositionX(playerData.pos_x);
                            divers[i].SetPositionY(playerData.pos_y);
                            found = true;
                        }
                    }
                }
            }
        }
    }
Exemple #7
0
        public void TopicPubSub()
        {
            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                var port = pub.BindRandomPort("tcp://127.0.0.1");
                sub.Connect("tcp://127.0.0.1:" + port);
                sub.Subscribe("A");

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

                pub.SendMoreFrame("A").SendFrame("Hello");

                CollectionAssert.AreEqual(
                    new[] {"A", "Hello"},
                    sub.ReceiveMultipartStrings());
            }
        }
Exemple #8
0
        public void LargeMessage()
        {
            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                var port = pub.BindRandomPort("tcp://127.0.0.1");
                sub.Connect("tcp://127.0.0.1:" + port);
                sub.Subscribe("");

                Thread.Sleep(100);

                var msg = new byte[300];

                pub.SendFrame(msg);

                byte[] msg2 = sub.ReceiveFrameBytes();

                Assert.AreEqual(300, msg2.Length);
            }
        }
        public void PubSub_Should_Not_Crash_If_No_Thread_Sleep()
        {
            NUnitUtils.PrintTestName();
            var swAll = Stopwatch.StartNew();

            using (var pub = new PublisherSocket())
            {
                using (var sub = new SubscriberSocket())
                {
                    var freePort = NUnitUtils.TcpPortFree();
                    pub.Bind("tcp://127.0.0.1:" + freePort);
                    sub.Connect("tcp://127.0.0.1:" + freePort);

                    sub.Subscribe("*");

                    var sw = Stopwatch.StartNew();
                    {
                        for (var i = 0; i < 50; i++)
                        {
                            pub.SendFrame("*"); // Ping.

                            Console.Write("*");
                            string topic;
                            var gotTopic = sub.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out topic);
                            string ping;
                            var gotPing = sub.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out ping);
                            if (gotTopic)
                            {
                                Console.Write("\n");
                                break;
                            }
                        }
                    }
                    Console.WriteLine("Connected in {0} ms.", sw.ElapsedMilliseconds);
                }
            }
            NUnitUtils.PrintElapsedTime(swAll.Elapsed);
        }
Exemple #10
0
        public void MultipleLargeMessages()
        {
            var largeMessage = new byte[12000];

            for (int i = 0; i < 12000; i++)
            {
                largeMessage[i] = (byte)(i % 256);
            }

            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                var port = pub.BindRandomPort("tcp://127.0.0.1");
                sub.Connect("tcp://127.0.0.1:" + port);
                sub.Subscribe("");

                Thread.Sleep(1000);

                pub.SendFrame("");
                sub.SkipFrame();

                for (int i = 0; i < 100; i++)
                {
                    pub.SendFrame(largeMessage);

                    byte[] recvMesage = sub.ReceiveFrameBytes();

                    for (int j = 0; j < 12000; j++)
                    {
                        Assert.AreEqual(largeMessage[j], recvMesage[j]);
                    }
                }
            }
        }
Exemple #11
0
        public void Sending1000Messages()
        {
            // creating two different context and sending 1000 messages

            int count = 0;

            var subReady = new ManualResetEvent(false);

            Task subTask = Task.Factory.StartNew(() =>
            {
                using (var sub = new SubscriberSocket())
                {
                    sub.Bind("pgm://224.0.0.1:5555");
                    sub.Subscribe("");

                    subReady.Set();

                    while (count < 1000)
                    {
                        bool more;
                        Assert.AreEqual(count, BitConverter.ToInt32(sub.ReceiveFrameBytes(out more), 0));
                        Assert.IsFalse(more);
                        count++;
                    }
                }
            });

            subReady.WaitOne();

            Task pubTask = Task.Factory.StartNew(() =>
            {
                using (var pub = new PublisherSocket())
                {
                    pub.Connect("pgm://224.0.0.1:5555");

                    for (int i = 0; i < 1000; i++)
                        pub.SendFrame(BitConverter.GetBytes(i));

                    // if we close the socket before the subscriber receives all messages subscriber
                    // might miss messages, lets wait another second
                    Thread.Sleep(1000);
                }
            });

            pubTask.Wait();
            subTask.Wait();

            Assert.AreEqual(1000, count);
        }
        public void Test_Two_Subscribers()
        {
            NUnitUtils.PrintTestName();
            var sw = Stopwatch.StartNew();

            using (var pub = new PublisherSocket())
            {
                using (var sub1 = new SubscriberSocket())
                {
                    using (var sub2 = new SubscriberSocket())
                    {
                        var freePort = NUnitUtils.TcpPortFree();
                        pub.Bind("tcp://127.0.0.1:" + freePort);
                        sub1.Connect("tcp://127.0.0.1:" + freePort);
                        sub1.Subscribe("A");
                        sub2.Connect("tcp://127.0.0.1:" + freePort);
                        sub2.Subscribe("B");

                        Thread.Sleep(500);

                        var swInner = Stopwatch.StartNew();
                        {
                            pub.SendFrame("A\n"); // Ping.
                            {
                                string topic;
                                var pass1 = sub1.TryReceiveFrameString(TimeSpan.FromMilliseconds(250), out topic);
                                if (pass1)
                                {
                                    Console.Write(topic);
                                }
                                else
                                {
                                    Assert.Fail();
                                }
                            }
                            pub.SendFrame("B\n"); // Ping.
                            {
                                string topic;
                                var pass2 = sub2.TryReceiveFrameString(TimeSpan.FromMilliseconds(250), out topic);
                                if (pass2)
                                {
                                    Console.Write(topic);
                                }
                                else
                                {
                                    Assert.Fail();
                                }
                            }
                        }
                        Console.WriteLine("Connected in {0} ms.", swInner.ElapsedMilliseconds);
                    }
                }
            }

            NUnitUtils.PrintElapsedTime(sw.Elapsed);
        }
Exemple #13
0
        public void SetPgmSettings()
        {
            const int MegaBit = 1024;
            const int MegaByte = 1024;

            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                pub.Options.MulticastHops = 2;
                pub.Options.MulticastRate = 40*MegaBit; // 40 megabit
                pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10);
                pub.Options.SendBuffer = MegaByte*10; // 10 megabyte

                pub.Connect("pgm://224.0.0.1:5555");

                sub.Options.ReceiveBuffer = MegaByte*10;
                sub.Bind("pgm://224.0.0.1:5555");

                sub.Subscribe("");

                pub.SendFrame("Hi");

                bool more;
                Assert.AreEqual("Hi", sub.ReceiveFrameString(out more));
                Assert.IsFalse(more);

                Assert.AreEqual(2, pub.Options.MulticastHops);
                Assert.AreEqual(40*MegaBit, pub.Options.MulticastRate);
                Assert.AreEqual(TimeSpan.FromMinutes(10), pub.Options.MulticastRecoveryInterval);
                Assert.AreEqual(MegaByte*10, pub.Options.SendBuffer);
                Assert.AreEqual(MegaByte*10, sub.Options.ReceiveBuffer);
            }
        }
Exemple #14
0
        public void ClearWelcomeMessage()
        {
            using (var pub = new XPublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                pub.Bind("inproc://welcome");
                pub.SetWelcomeMessage("W");
                pub.ClearWelcomeMessage();

                sub.Subscribe("W");
                sub.Connect("inproc://welcome");

                var subscription = pub.ReceiveFrameBytes();

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

                Assert.IsFalse(sub.TrySkipFrame());
            }
        }
Exemple #15
0
        public void ThroughXPubXSubWithReconnectingPublisher()
        {
            using (var xpub = new XPublisherSocket())
            using (var xsub = new XSubscriberSocket())
            using (var poller = new NetMQPoller {xsub, xpub})
            {
                var xPubPort = (ushort)xpub.BindRandomPort("tcp://*");
                var xSubPort = (ushort)xsub.BindRandomPort("tcp://*");

                var proxy = new Proxy(xsub, xpub, poller: poller);
                proxy.Start();

                poller.RunAsync();

                // long running subscriber
                using (var sub = new SubscriberSocket())
                {
                    sub.Connect(string.Format("tcp://localhost:{0}", xPubPort));
                    sub.Subscribe("A");

                    // publisher 1
                    using (var pub = new PublisherSocket())
                    {
                        pub.Connect(string.Format("tcp://localhost:{0}", xSubPort));
                        // give the publisher a chance to learn of the subscription
                        Thread.Sleep(100);
                        pub.SendMoreFrame("A").SendFrame("1");
                    }

                    // publisher 2
                    using (var pub = new PublisherSocket())
                    {
                        pub.Connect(string.Format("tcp://localhost:{0}", xSubPort));
                        // give the publisher a chance to learn of the subscription
                        Thread.Sleep(100);
                        pub.SendMoreFrame("A").SendFrame("2");
                    }

                    var frames = new List<string>();

                    Assert.True(sub.TryReceiveMultipartStrings(TimeSpan.FromSeconds(1), ref frames));
                    CollectionAssert.AreEqual(new[] { "A", "1" }, frames);

                    Assert.True(sub.TryReceiveMultipartStrings(TimeSpan.FromSeconds(1), ref frames));
                    CollectionAssert.AreEqual(new[] { "A", "2" }, frames);
                }
            }
        }
Exemple #16
0
        public void ThroughXPubXSub()
        {
            using (var xpub = new XPublisherSocket())
            using (var xsub = new XSubscriberSocket())
            using (var proxyPoller = new NetMQPoller {xsub, xpub})
            {
                var xPubPort = (ushort)xpub.BindRandomPort("tcp://*");
                var xSubPort = (ushort)xsub.BindRandomPort("tcp://*");

                var proxy = new Proxy(xsub, xpub, poller: proxyPoller);
                proxy.Start();

                proxyPoller.RunAsync();

                using (var pub = new PublisherSocket())
                using (var sub = new SubscriberSocket())
                {
                    // Client 1
                    sub.Connect(string.Format("tcp://localhost:{0}", xPubPort));
                    pub.Connect(string.Format("tcp://localhost:{0}", xSubPort));

                    sub.Subscribe("A");

                    // Client 2
                    Thread.Sleep(500);
                    pub.SendMoreFrame("A").SendFrame("Hello");

                    var frames = new List<string>();
                    Assert.True(sub.TryReceiveMultipartStrings(TimeSpan.FromSeconds(1), ref frames));
                    CollectionAssert.AreEqual(
                        new[] { "A", "Hello" },
                        frames);
                }
            }
        }
Exemple #17
0
        public void MultiplePublishersAndSubscribersOnSameTopic()
        {
            using (var pub1 = new PublisherSocket())
            using (var pub2 = new PublisherSocket())
            using (var sub1 = new SubscriberSocket())
            using (var sub2 = new SubscriberSocket())
            {
                int port1 = pub1.BindRandomPort("tcp://127.0.0.1");
                int port2 = pub2.BindRandomPort("tcp://127.0.0.1");

                sub1.Connect("tcp://127.0.0.1:" + port1);
                sub1.Connect("tcp://127.0.0.1:" + port2);

                sub2.Connect("tcp://127.0.0.1:" + port1);
                sub2.Connect("tcp://127.0.0.1:" + port2);

                // should subscribe to both
                sub1.Subscribe("A");
                sub2.Subscribe("A");

                Thread.Sleep(500);

                // Send from pub 1
                pub1.SendMoreFrame("A").SendFrame("Hello from the first publisher");

                CollectionAssert.AreEqual(new[] { "A", "Hello from the first publisher" }, sub1.ReceiveMultipartStrings());
                CollectionAssert.AreEqual(new[] { "A", "Hello from the first publisher" }, sub2.ReceiveMultipartStrings());

                // Send from pub 2
                pub2.SendMoreFrame("A").SendFrame("Hello from the second publisher");

                CollectionAssert.AreEqual(new[] { "A", "Hello from the second publisher" }, sub1.ReceiveMultipartStrings());
                CollectionAssert.AreEqual(new[] { "A", "Hello from the second publisher" }, sub2.ReceiveMultipartStrings());
            }
        }
Exemple #18
0
        public void LargerBufferLength()
        {
            var largerBuffer = new byte[256];
            {
                largerBuffer[124] = 0xD;
                largerBuffer[125] = 0xE;
                largerBuffer[126] = 0xE;
                largerBuffer[127] = 0xD;
            }

            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                var port = pub.BindRandomPort("tcp://127.0.0.1");
                sub.Connect("tcp://127.0.0.1:" + port);
                sub.Subscribe("");

                Thread.Sleep(100);

                pub.SendFrame(largerBuffer, 128);

                byte[] recvMesage = sub.ReceiveFrameBytes();

                Assert.AreEqual(128, recvMesage.Length);
                Assert.AreEqual(0xD, recvMesage[124]);
                Assert.AreEqual(0xE, recvMesage[125]);
                Assert.AreEqual(0xE, recvMesage[126]);
                Assert.AreEqual(0xD, recvMesage[127]);

                Assert.AreNotEqual(largerBuffer.Length, recvMesage.Length);
            }
        }
Exemple #19
0
        public void UseInterface()
        {
            #if NETCOREAPP1_0
            var hostEntry = Dns.GetHostEntryAsync(Dns.GetHostName()).Result;
            #else
            var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            #endif

            string ip = hostEntry.AddressList
                .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork)
                .Select(addr => addr.ToString())
                .FirstOrDefault();

            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                pub.Connect($"pgm://{ip};224.0.0.1:5555");
                sub.Bind($"pgm://{ip};224.0.0.1:5555");

                sub.Subscribe("");

                pub.SendFrame("Hi");

                bool more;
                Assert.AreEqual("Hi", sub.ReceiveFrameString(out more));
                Assert.IsFalse(more);
            }
        }
Exemple #20
0
        public void ReceiveMessageWithTimeout()
        {
            {
                var pubSync = new AutoResetEvent(false);
                var payload = new byte[300];
                const int waitTime = 500;

                var t1 = new Task(() =>
                {
                    using (var pubSocket = new PublisherSocket())
                    {
                        pubSocket.Bind("tcp://127.0.0.1:12345");
                        pubSync.WaitOne();
                        Thread.Sleep(waitTime);
                        pubSocket.SendFrame(payload);
                        pubSync.WaitOne();
                    }
                }, TaskCreationOptions.LongRunning);

                var t2 = new Task(() =>
                {
                    using (var subSocket = new SubscriberSocket())
                    {
                        subSocket.Connect("tcp://127.0.0.1:12345");
                        subSocket.Subscribe("");
                        Thread.Sleep(100);
                        pubSync.Set();

                        NetMQMessage msg = null;
                        Assert.IsFalse(subSocket.TryReceiveMultipartMessage(TimeSpan.FromMilliseconds(100), ref msg));

                        Assert.IsTrue(subSocket.TryReceiveMultipartMessage(TimeSpan.FromMilliseconds(waitTime), ref msg));
                        Assert.NotNull(msg);
                        Assert.AreEqual(1, msg.FrameCount);
                        Assert.AreEqual(300, msg.First.MessageSize);
                        pubSync.Set();
                    }
                }, TaskCreationOptions.LongRunning);

                t1.Start();
                t2.Start();

                Task.WaitAll(t1, t2);
            }
        }
Exemple #21
0
        public void MultipleSubscribersOnDifferentTopics()
        {
            using (var pub = new PublisherSocket())
            using (var sub1 = new SubscriberSocket())
            using (var sub2 = new SubscriberSocket())
            {
                var port = pub.BindRandomPort("tcp://127.0.0.1");

                sub1.Connect("tcp://127.0.0.1:" + port);
                sub2.Connect("tcp://127.0.0.1:" + port);

                sub1.Subscribe("1");
                sub1.Subscribe("1&2");

                sub2.Subscribe("2");
                sub2.Subscribe("1&2");

                Thread.Sleep(500);

                pub.SendMoreFrame("1").SendFrame("A");

                CollectionAssert.AreEqual(new[] { "1", "A" }, sub1.ReceiveMultipartStrings());
                Assert.IsFalse(sub2.TrySkipFrame());

                pub.SendMoreFrame("2").SendFrame("B");

                Assert.IsFalse(sub1.TrySkipFrame());
                CollectionAssert.AreEqual(new[] { "2", "B" }, sub2.ReceiveMultipartStrings());

                pub.SendMoreFrame("1&2").SendFrame("C");

                CollectionAssert.AreEqual(new[] { "1&2", "C" }, sub1.ReceiveMultipartStrings());
                CollectionAssert.AreEqual(new[] { "1&2", "C" }, sub2.ReceiveMultipartStrings());
            }
        }
Exemple #22
-1
        public void LargeMessage()
        {
            using (var pub = new PublisherSocket())
            using (var sub = new SubscriberSocket())
            {
                pub.Connect("pgm://224.0.0.1:5555");
                sub.Bind("pgm://224.0.0.1:5555");

                sub.Subscribe("");

                var data = new byte[3200]; // this should be at least 3 packets

                for (Int16 i = 0; i < 1600; i++)
                    Array.Copy(BitConverter.GetBytes(i), 0, data, i*2, 2);

                pub.SendFrame(data);

                byte[] message = sub.ReceiveFrameBytes();

                Assert.AreEqual(3200, message.Length);

                for (Int16 i = 0; i < 1600; i++)
                    Assert.AreEqual(i, BitConverter.ToInt16(message, i*2));
            }
        }