Publisher socket, is the pub in pubsub pattern. publish a message to all subscribers which subscribed for the topic
Inheritance: NetMQSocket
示例#1
0
        /// <summary>
        /// Try to send request message and return the response as a message, or return null if not successful
        /// </summary>
        /// <param name="address">a string denoting the address to connect to</param>
        /// <param name="requestMessage">The request message</param>
        /// <param name="numTries">The number of times to try</param>
        /// <param name="requestTimeout">The timeout for each request</param>
        /// <param name="progressPublisher">Report topics: Failure, Retry, Send, Success</param>
        /// <returns>the response message, or null if not successful</returns>
        public static NetMQMessage RequestResponseMultipartMessageWithRetry([NotNull] string address, [NotNull] NetMQMessage requestMessage,
            int numTries, TimeSpan requestTimeout, PublisherSocket progressPublisher = null)
        {
            var responseMessage = new NetMQMessage();

            while (numTries-- > 0)
            {
                using (var requestSocket = new RequestSocket(address))
                {
                    progressPublisher?.SendFrame(ProgressTopic.Send.ToString());

                    requestSocket.SendMultipartMessage(requestMessage);

                    if (requestSocket.TryReceiveMultipartMessage(requestTimeout, ref responseMessage))
                    {
                        progressPublisher?.SendFrame(ProgressTopic.Success.ToString());

                        return responseMessage;
                    }

                    progressPublisher?.SendFrame(ProgressTopic.Retry.ToString());
                }
            }

            progressPublisher?.SendFrame(ProgressTopic.Failure.ToString());

            return null;
        }
示例#2
0
        public void BindRandomThenUnbind()
        {
            using (var pub = new PublisherSocket())
            {
                var port = pub.BindRandomPort("tcp://localhost");

                pub.Unbind("tcp://localhost:" + port);
            }

            using (var pub = new PublisherSocket())
            {
                var port = pub.BindRandomPort("tcp://*");

                pub.Unbind("tcp://*:" + port);
            }

            using (var pub = new PublisherSocket())
            {
                var port1 = pub.BindRandomPort("tcp://*");
                var port2 = pub.BindRandomPort("tcp://*");
                var port3 = pub.BindRandomPort("tcp://*");

                pub.Unbind("tcp://*:" + port1);
                pub.Unbind("tcp://*:" + port2);
                pub.Unbind("tcp://*:" + port3);
            }
        }
示例#3
0
        public void RequestResponseMultipartMessageWithRetryFails()
        {
            const string address = "tcp://127.0.0.1:50002";
            const string pubAddress = "tcp://127.0.0.1:60002";
            const int numTries = 5;
            var requestTimeout = TimeSpan.FromMilliseconds(100);
            var requestMessage = new NetMQMessage(1);
            requestMessage.Append("Hi");

            using (var progressPublisher = new PublisherSocket(pubAddress))
            using (var progressSubscriber = new SubscriberSocket(pubAddress))
            using (var server = new RouterSocket(address))
            {
                progressSubscriber.SubscribeToAnyTopic();
                var progressProactor = new NetMQProactor(progressSubscriber, (socket, message) =>
                    Console.WriteLine("C: {0} {1:ss.fff}", message[0].ConvertToString(), DateTime.Now));

                var serverProactor = new NetMQProactor(server, (socket, message) =>
                {
                    Console.WriteLine("ResponseEcho recieved message {0} at {1:ss.fff}", message[2].ConvertToString(),
                        DateTime.Now);
                });

                using (serverProactor)
                using (progressProactor)
                {
                    var responseMessage = RequestSocket.RequestResponseMultipartMessageWithRetry(address, requestMessage,
                        numTries, requestTimeout, progressPublisher);
                    Assert.IsNull(responseMessage);
                }
            }
        }
示例#4
0
    /* =====================
     * 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.
    }
示例#6
0
    public void init(string address, int port)
    {
        this.address = address;
        this.port    = port;

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

        //create client
        publisher = context.CreatePublisherSocket();

        //connect publisher
        publisher.Bind("tcp://" + address + ":" + port);
    }
        public void HandleMessage(Message message, RouterSocket serverSocket, PublisherSocket ioPub)
        {
            KernelInfoRequest kernelInfoRequest = JsonSerializer.Deserialize<KernelInfoRequest>(message.Content);

            Message replyMessage = new Message()
            {
                UUID = message.Header.Session,
                ParentHeader = message.Header,
                Header = MessageBuilder.CreateHeader(MessageTypeValues.KernelInfoReply, message.Header.Session),
                Content = JsonSerializer.Serialize(this.CreateKernelInfoReply())
            };

            this.logger.Info("Sending kernel_info_reply");
            MessageSender.Send(replyMessage, serverSocket);
        }
示例#8
0
        public void NotSubscribed()
        {
            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);

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

                pub.SendFrame("Hello");

                Assert.IsFalse(sub.TrySkipFrame());
            }
        }
示例#9
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);
            }
        }
示例#10
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());
            }
        }
示例#11
0
        public void HandleMessage(Message message, RouterSocket serverSocket, PublisherSocket ioPub)
        {
            this.logger.Debug(string.Format("Message Content {0}", message.Content));
            ExecuteRequest executeRequest = JsonSerializer.Deserialize<ExecuteRequest>(message.Content);

            this.logger.Info(string.Format("Execute Request received with code {0}", executeRequest.Code));

            // 1: Send Busy status on IOPub
            this.SendMessageToIOPub(message, ioPub, StatusValues.Busy);

            // 2: Send execute input on IOPub
            this.SendInputMessageToIOPub(message, ioPub, executeRequest.Code);

            // 3: Evaluate the C# code
            string code = executeRequest.Code;
            ExecutionResult results = this.replEngine.Execute(code);
            string codeOutput = this.GetCodeOutput(results);
            string codeHtmlOutput = this.GetCodeHtmlOutput(results);
            
            Dictionary<string, object> data = new Dictionary<string, object>()
            {
                {"text/plain", codeOutput},
                {"text/html", codeHtmlOutput}
            };

            DisplayData displayData = new DisplayData()
            {
                Data = data,
            };

            // 4: Send execute reply to shell socket
            this.SendExecuteReplyMessage(message, serverSocket);

            // 5: Send execute result message to IOPub
            this.SendOutputMessageToIOPub(message, ioPub, displayData);

            // 6: Send IDLE status message to IOPub
            this.SendMessageToIOPub(message, ioPub, StatusValues.Idle);

            this.executionCount += 1;

        }
示例#12
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);
            }
        }
示例#13
0
        public void RequestResponseMultipartMessageWithRetrySucceedsFirstTry()
        {
            const string address = "tcp://127.0.0.1:50001";
            const string pubAddress = "tcp://127.0.0.1:60001";
            const int numTries = 5;
            var requestTimeout = TimeSpan.FromMilliseconds(100);
            var requestMessage = new NetMQMessage(1);
            requestMessage.Append("Hi");

            using (var progressPublisher = new PublisherSocket(pubAddress))
            using (var progressSubscriber = new SubscriberSocket(pubAddress))
            using (var server = new ResponseSocket(address))
            {
                progressSubscriber.SubscribeToAnyTopic();
                var progressProactor = new NetMQProactor(progressSubscriber, (socket, message) =>
                    Console.WriteLine("C: {0} {1:ss.fff}", message[0].ConvertToString(), DateTime.Now));

                var serverProactor = new NetMQProactor(server, (socket, message) =>
                {
                    Console.WriteLine("ResponseEcho received message {0} at {1:ss.fff}", message.First.ConvertToString(),
                        DateTime.Now);

                    // reply same message
                    socket.SendMultipartMessage(message);
                });

                using (serverProactor)
                using (progressProactor)
                {
                    var responseMessage = RequestSocket.RequestResponseMultipartMessageWithRetry(address,
                        requestMessage, numTries, requestTimeout, progressPublisher);
                    Assert.IsNotNull(responseMessage);
                    Assert.AreEqual(1, responseMessage.FrameCount);
                    var responseString = responseMessage.First.ConvertToString();
                    Assert.AreEqual("Hi", responseString);
                }
            }
        }
        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);
        }
示例#15
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);
            }
        }
示例#16
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);
            }
        }
示例#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());
            }
        }
示例#18
0
        /// <summary>
        /// Try to send request string and return the response string, or return null if not successful
        /// </summary>
        /// <param name="address">a string denoting the address to connect to</param>
        /// <param name="requestString">The request string</param>
        /// <param name="numTries">The number of times to try</param>
        /// <param name="requestTimeout">The timeout for each request</param>
        /// <param name="progressPublisher">Report topics: Failure, Retry, Send, Success</param>
        /// <returns>the response message, or null if not successful</returns>
        public static string RequestResponseStringWithRetry([NotNull] string address, [NotNull] string requestString,
            int numTries, TimeSpan requestTimeout, PublisherSocket progressPublisher = null)
        {
            while (numTries-- > 0)
            {
                using (var requestSocket = new RequestSocket(address))
                {
                    if (progressPublisher != null)
                    {
                        progressPublisher.SendFrame(ProgressTopic.Send.ToString());
                    }

                    requestSocket.SendFrame(requestString);

                    string frameString;
                    if (requestSocket.TryReceiveFrameString(requestTimeout, out frameString))
                    {
                        if (progressPublisher != null)
                        {
                            progressPublisher.SendFrame(ProgressTopic.Success.ToString());
                        }

                        return frameString;
                    }
                    if (progressPublisher != null)
                    {
                        progressPublisher.SendFrame(ProgressTopic.Retry.ToString());
                    }
                }
            }

            if (progressPublisher != null)
            {
                progressPublisher.SendFrame(ProgressTopic.Failure.ToString());
            }

            return null;
        }
示例#19
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);
                }
            }
        }
示例#20
0
        public void RequestResponseStringWithRetrySucceedsNotOnFirstTry()
        {
            const string address = "tcp://127.0.0.1:50001";
            const string pubAddress = "tcp://127.0.0.1:60001";
            const int numTries = 5;
            var requestTimeout = TimeSpan.FromMilliseconds(100);

            using (var progressPublisher = new PublisherSocket(pubAddress))
            using (var progressSubscriber = new SubscriberSocket(pubAddress))
            using (var server = new RouterSocket(address))
            {
                progressSubscriber.SubscribeToAnyTopic();
                var progressProactor = new NetMQProactor(progressSubscriber, (socket, message) =>
                    Console.WriteLine("C: {0} {1:ss.fff}", message[0].ConvertToString(), DateTime.Now));

                int attempt = 0;

                var serverProactor = new NetMQProactor(server, (socket, message) =>
                {
                    Console.WriteLine("ResponseEcho recieved message {0} at {1:ss.fff}", message[2].ConvertToString(),
                        DateTime.Now);

                    attempt++;

                    if (attempt > 1)
                    {
                        // reply same message
                        socket.SendMultipartMessage(message);
                    }
                });

                using (serverProactor)
                using (progressProactor)
                {
                    var responseMessage = RequestSocket.RequestResponseStringWithRetry(address,
                        "Hi", numTries, requestTimeout, progressPublisher);
                    Assert.AreEqual("Hi", responseMessage);
                }
            }
        }
示例#21
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);
        }
示例#22
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);
                }
            }
        }
示例#23
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);
            }
        }
示例#24
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());
            }
        }
        public void SendMessageToIOPub(Message message, PublisherSocket ioPub, string statusValue)
        {
            Dictionary<string,string> content = new Dictionary<string, string>();
            content.Add("execution_state", statusValue);
            Message ioPubMessage = MessageBuilder.CreateMessage(MessageTypeValues.Status,
                JsonSerializer.Serialize(content), message.Header);

            this.logger.Info(string.Format("Sending message to IOPub {0}", JsonSerializer.Serialize(ioPubMessage)));
            MessageSender.Send(ioPubMessage, ioPub);
            this.logger.Info("Message Sent");
        }
示例#26
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);
            }
        }
        public void SendInputMessageToIOPub(Message message, PublisherSocket ioPub, string code)
        {
            Dictionary<string, object> content = new Dictionary<string, object>();
            content.Add("execution_count", 1);
            content.Add("code", code);

            Message executeInputMessage = MessageBuilder.CreateMessage(MessageTypeValues.Input, JsonSerializer.Serialize(content),
                message.Header);

            this.logger.Info(string.Format("Sending message to IOPub {0}", JsonSerializer.Serialize(executeInputMessage)));
            MessageSender.Send(executeInputMessage, ioPub);
        }
		private PublisherSocket GetNewPublisherSocket(string addressZeroMq)
		{
			PublisherSocket publisherSocket;
			{
				_loggerDelegate?.Invoke(string.Format("Publisher socket binding to: {0}\n", addressZeroMq));

				publisherSocket = new PublisherSocket();

				// Corner case: wait until publisher socket is ready (see code below that waits for
				// "_publisherReadySignal").
				NetMQMonitor monitor;
				{
					// Must ensure that we have a unique monitor name for every instance of this class.
					string endPoint = string.Format("inproc://#SubjectNetMQ#Publisher#{0}#{1}", addressZeroMq, Guid.NewGuid().ToString());
					monitor = new NetMQMonitor(publisherSocket,
						endPoint,
						SocketEvents.Accepted | SocketEvents.Listening
						);
					monitor.Accepted += Publisher_Event_Accepted;                    
                    monitor.Listening += Publisher_Event_Listening;
					monitor.StartAsync();
				}

				publisherSocket.Options.SendHighWatermark = this.HighwaterMark;
				try
				{
					publisherSocket.Bind(addressZeroMq);
				}
				catch (NetMQException ex)
				{
					// This is usually because the address is in use.
					throw new Exception(string.Format("Error E56874. Cannot bind publisher to '{0}'. 95% probability that this is caused by trying to bind a publisher to a port already in use by another process. To fix, choose a unique publisher port for this process. For more on this error, see 'Readme.md' (or the GitHub homepage for NetMQ.ReactiveExtensions).", addressZeroMq), ex);
				}
				
				// Corner case: wait until publisher socket is ready (see code below that sets "_publisherReadySignal").
				{
					Stopwatch sw = Stopwatch.StartNew();
					_publisherReadySignal.WaitOne(TimeSpan.FromMilliseconds(3000));
					_loggerDelegate?.Invoke(string.Format("Publisher: Waited {0} ms for binding.\n", sw.ElapsedMilliseconds));
				}
				{
					monitor.Accepted -= Publisher_Event_Accepted;
					monitor.Listening -= Publisher_Event_Listening;
					// Current issue with NegMQ: Cannot stop or dispose monitor, or else it stops the parent socket.
					//monitor.Stop();
					//monitor.Dispose();
				}
			}

            // Otherwise, the first item we publish may get missed by the subscriber. 500 milliseconds consistently works 
            // locally, but occasionally fails on the AppVeyor build server. 650 milliseconds is optimal.
            using (EventWaitHandle wait = new ManualResetEvent(false))
            {
                // Cannot use Thread.Sleep() here, as this is incompatible with .NET Core 1.0, Windows 8.0, 8.1, and 10.
                wait.WaitOne(TimeSpan.FromMilliseconds(650));
            }

            return publisherSocket;
		}
        public void SendOutputMessageToIOPub(Message message, PublisherSocket ioPub, DisplayData data)
        {
            Dictionary<string,object> content = new Dictionary<string, object>();
            content.Add("execution_count", this.executionCount);
            content.Add("data", data.Data);
            content.Add("metadata", data.MetaData);

            Message outputMessage = MessageBuilder.CreateMessage(MessageTypeValues.Output,
                JsonSerializer.Serialize(content), message.Header);

            this.logger.Info(string.Format("Sending message to IOPub {0}", JsonSerializer.Serialize(outputMessage)));
            MessageSender.Send(outputMessage, ioPub);
        }
示例#30
0
        public void HandleMessage(Message message, RouterSocket serverSocket, PublisherSocket ioPub)
        {
            CompleteRequest completeRequest = JsonSerializer.Deserialize<CompleteRequest>(message.Content);

            // TODO: Send reply
        }
示例#31
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]);
                    }
                }
            }
        }
        /// <summary>
        /// Try to send request message and return the response as a message, or return null if not successful
        /// </summary>
        /// <param name="address">a string denoting the address to connect to</param>
        /// <param name="requestMessage">The request message</param>
        /// <param name="numTries">The number of times to try</param>
        /// <param name="requestTimeout">The timeout for each request</param>
        /// <param name="progressPublisher">Report topics: Failure, Retry, Send, Success</param>
        /// <returns>the response message, or null if not successful</returns>
        public static NetMQMessage RequestResponseMultipartMessageWithRetry(string address, NetMQMessage requestMessage,
                                                                            int numTries, TimeSpan requestTimeout, PublisherSocket progressPublisher = null)
        {
            var responseMessage = new NetMQMessage();

            while (numTries-- > 0)
            {
                using (var requestSocket = new RequestSocket(address))
                {
                    if (progressPublisher != null)
                    {
                        progressPublisher.SendFrame(ProgressTopic.Send.ToString());
                    }

                    requestSocket.SendMultipartMessage(requestMessage);

                    if (requestSocket.TryReceiveMultipartMessage(requestTimeout, ref responseMessage))
                    {
                        if (progressPublisher != null)
                        {
                            progressPublisher.SendFrame(ProgressTopic.Success.ToString());
                        }

                        return(responseMessage);
                    }

                    if (progressPublisher != null)
                    {
                        progressPublisher.SendFrame(ProgressTopic.Retry.ToString());
                    }
                }
            }


            if (progressPublisher != null)
            {
                progressPublisher.SendFrame(ProgressTopic.Failure.ToString());
            }

            return(null);
        }
示例#33
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);
            }
        }
        /// <summary>
        /// Try to send request string and return the response string, or return null if not successful
        /// </summary>
        /// <param name="address">a string denoting the address to connect to</param>
        /// <param name="requestString">The request string</param>
        /// <param name="numTries">The number of times to try</param>
        /// <param name="requestTimeout">The timeout for each request</param>
        /// <param name="progressPublisher">Report topics: Failure, Retry, Send, Success</param>
        /// <returns>the response message, or null if not successful</returns>
        public static string RequestResponseStringWithRetry(string address, string requestString,
                                                            int numTries, TimeSpan requestTimeout, PublisherSocket progressPublisher = null)
        {
            while (numTries-- > 0)
            {
                using (var requestSocket = new RequestSocket(address))
                {
                    if (progressPublisher != null)
                    {
                        progressPublisher.SendFrame(ProgressTopic.Send.ToString());
                    }

                    requestSocket.SendFrame(requestString);

                    string frameString;
                    if (requestSocket.TryReceiveFrameString(requestTimeout, out frameString))
                    {
                        if (progressPublisher != null)
                        {
                            progressPublisher.SendFrame(ProgressTopic.Success.ToString());
                        }

                        return(frameString);
                    }
                    if (progressPublisher != null)
                    {
                        progressPublisher.SendFrame(ProgressTopic.Retry.ToString());
                    }
                }
            }

            if (progressPublisher != null)
            {
                progressPublisher.SendFrame(ProgressTopic.Failure.ToString());
            }

            return(null);
        }
示例#35
-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));
            }
        }