예제 #1
2
파일: ProxyTests.cs 프로젝트: GrabCAD/netmq
        public void SendAndReceive()
        {
            using (var front = new RouterSocket())
            using (var back = new DealerSocket())
            {
                front.Bind("inproc://frontend");
                back.Bind("inproc://backend");

                var proxy = new Proxy(front, back);
                Task.Factory.StartNew(proxy.Start);

                using (var client = new RequestSocket())
                using (var server = new ResponseSocket())
                {
                    client.Connect("inproc://frontend");
                    server.Connect("inproc://backend");

                    client.SendFrame("hello");
                    Assert.AreEqual("hello", server.ReceiveFrameString());
                    server.SendFrame("reply");
                    Assert.AreEqual("reply", client.ReceiveFrameString());
                }

                proxy.Stop();
            }
        }
예제 #2
0
        public void RouterDealerMessaging()
        {            
            using (var server = new RouterSocket())
            using (var client = new DealerSocket())
            {
                int port = server.BindRandomPort("tcp://127.0.0.1");
                client.Connect("tcp://127.0.0.1:" + port);

                var clientOutgoingMessage = new NetMQMessage();
                clientOutgoingMessage.Append("Hello");

                client.SendMultipartMessage(clientOutgoingMessage);

                NetMQMessage serverIncomingMessage = server.ReceiveMultipartMessage();

                // number of frames should be one because first message should be identity of client
                Assert.AreEqual(2, serverIncomingMessage.FrameCount);
                Assert.AreEqual("Hello", serverIncomingMessage[1].ConvertToString());

                var serverOutgoingMessage = new NetMQMessage();

                // first adding the identity
                serverOutgoingMessage.Append(serverIncomingMessage[0]);
                serverOutgoingMessage.Append("World");

                server.SendMultipartMessage(serverOutgoingMessage);

                var incomingClientMessage = client.ReceiveMultipartMessage();

                Assert.AreEqual(1, incomingClientMessage.FrameCount);
                Assert.AreEqual("World", incomingClientMessage[0].ConvertToString());
            }
        }
예제 #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
파일: SocketTests.cs 프로젝트: hdxhan/netmq
        public void CheckReceiveAgainException()
        {
            using (var router = new RouterSocket())
            {
                router.BindRandomPort("tcp://127.0.0.1");

                router.Receive(SendReceiveOptions.DontWait);
            }
        }
예제 #5
0
        public void DefaultValues()
        {            
            using (var socket = new RouterSocket())
            {
                Assert.IsNull(socket.Options.Identity);
//                Assert.IsNull(socket.Options.TcpAcceptFilter);
                Assert.AreEqual(false, socket.Options.ReceiveMore);
            }
        }
예제 #6
0
        public void Mandatory()
        {
            using (var router = new RouterSocket())
            {
                router.Options.RouterMandatory = true;
                router.BindRandomPort("tcp://*");

                Assert.Throws<HostUnreachableException>(() => router.SendMoreFrame("UNKNOWN").SendFrame("Hello"));
            }
        }
예제 #7
0
        public void ReceiveReadyDot35Bug()
        {
            // In .NET 3.5, we saw an issue where ReceiveReady would be raised every second despite nothing being received
            using (var server = new RouterSocket())
            {
                server.BindRandomPort("tcp://127.0.0.1");
                server.ReceiveReady += (s, e) => Assert.Fail("Should not receive");

                Assert.IsFalse(server.Poll(TimeSpan.FromMilliseconds(1500)));
            }
        }
예제 #8
0
        public void CheckTryReceive()
        {
            using (var router = new RouterSocket())
            {
                router.BindRandomPort("tcp://127.0.0.1");

                var msg = new Msg();
                msg.InitEmpty();
                Assert.IsFalse(router.TryReceive(ref msg, TimeSpan.Zero));
            }
        }
        public void SendExecuteReplyMessage(Message message, RouterSocket shellSocket)
        {
            ExecuteReplyOk executeReply = new ExecuteReplyOk()
            {
                ExecutionCount = this.executionCount,
                Payload = new List<Dictionary<string, string>>(),
                UserExpressions = new Dictionary<string, string>()
            };

            Message executeReplyMessage = MessageBuilder.CreateMessage(MessageTypeValues.ExecuteReply,
                JsonSerializer.Serialize(executeReply), message.Header);

            this.logger.Info(string.Format("Sending message to Shell {0}", JsonSerializer.Serialize(executeReplyMessage)));
            MessageSender.Send(executeReplyMessage, shellSocket);
        }
        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);
        }
예제 #11
0
        public void CheckTrySendSucceeds()
        {
            using (var router = new RouterSocket())
            using (var dealer = new DealerSocket())
            {
                var port = router.BindRandomPort("tcp://127.0.0.1");
                router.Options.Linger = TimeSpan.Zero;

                dealer.Options.SendHighWatermark = 1;
                dealer.Options.Linger = TimeSpan.Zero;
                dealer.Connect("tcp://127.0.0.1:" + port);

                Thread.Sleep(100);

                Assert.IsTrue(dealer.TrySendFrame("1"));
            }
        }
예제 #12
0
파일: SocketTests.cs 프로젝트: hdxhan/netmq
        public void CheckSendAgainException()
        {
            using (var router = new RouterSocket())
            using (var dealer = new DealerSocket())
            {
                var port = router.BindRandomPort("tcp://127.0.0.1");
                router.Options.Linger = TimeSpan.Zero;

                dealer.Options.SendHighWatermark = 1;
                dealer.Options.Linger = TimeSpan.Zero;
                dealer.Connect("tcp://127.0.0.1:" + port);

#pragma warning disable 618
                dealer.Send("1", dontWait: true, sendMore: false);
                dealer.Send("2", dontWait: true, sendMore: false);
#pragma warning restore 618
            }
        }
예제 #13
0
        public void TwoMessagesFromRouterToDealer()
        {
            using (var server = new RouterSocket())
            using (var client = new DealerSocket())
            using (var poller = new NetMQPoller { client })
            {
                var port = server.BindRandomPort("tcp://*");
                client.Connect("tcp://127.0.0.1:" + port);
                var cnt = 0;
                client.ReceiveReady += (sender, e) =>
                {
                    var strs = e.Socket.ReceiveMultipartStrings();
                    foreach (var str in strs)
                    {
                        Console.WriteLine(str);
                    }
                    cnt++;
                    if (cnt == 2)
                    {
                        poller.Stop();
                    }
                };
                byte[] clientId = Encoding.Unicode.GetBytes("ClientId");
                client.Options.Identity = clientId;

                const string request = "GET /\r\n";

                const string response = "HTTP/1.0 200 OK\r\n" +
                        "Content-Type: text/plain\r\n" +
                        "\r\n" +
                        "Hello, World!";

                client.SendFrame(request);

                byte[] serverId = server.ReceiveFrameBytes();
                Assert.AreEqual(request, server.ReceiveFrameString());

                // two messages in a row, not frames
                server.SendMoreFrame(serverId).SendFrame(response);
                server.SendMoreFrame(serverId).SendFrame(response);

                poller.Run();
            }
        }
예제 #14
0
파일: ProxyTests.cs 프로젝트: GrabCAD/netmq
        public void SeparateControlSocketsObservedMessages()
        {
            using (var front = new RouterSocket())
            using (var back = new DealerSocket())
            using (var controlInPush = new PushSocket())
            using (var controlInPull = new PullSocket())
            using (var controlOutPush = new PushSocket())
            using (var controlOutPull = new PullSocket())
            {
                front.Bind("inproc://frontend");
                back.Bind("inproc://backend");

                controlInPush.Bind("inproc://controlIn");
                controlInPull.Connect("inproc://controlIn");
                controlOutPush.Bind("inproc://controlOut");
                controlOutPull.Connect("inproc://controlOut");

                var proxy = new Proxy(front, back, controlInPush, controlOutPush);
                Task.Factory.StartNew(proxy.Start);

                using (var client = new RequestSocket())
                using (var server = new ResponseSocket())
                {
                    client.Connect("inproc://frontend");
                    server.Connect("inproc://backend");

                    client.SendFrame("hello");
                    Assert.AreEqual("hello", server.ReceiveFrameString());
                    server.SendFrame("reply");
                    Assert.AreEqual("reply", client.ReceiveFrameString());
                }

                Assert.IsNotNull(controlInPull.ReceiveFrameBytes());     // receive identity
                Assert.IsEmpty(controlInPull.ReceiveFrameString()); // pull terminator
                Assert.AreEqual("hello", controlInPull.ReceiveFrameString());

                Assert.IsNotNull(controlOutPull.ReceiveFrameBytes());     // receive identity
                Assert.IsEmpty(controlOutPull.ReceiveFrameString()); // pull terminator
                Assert.AreEqual("reply", controlOutPull.ReceiveFrameString());

                proxy.Stop();
            }
        }
예제 #15
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;

        }
예제 #16
0
파일: ZrePeerTests.cs 프로젝트: NetMQ/Zyre
        public void ZyrePeerTests()
        {
            var peers = new Dictionary<Guid, ZyrePeer>();
            var me = Guid.NewGuid();
            var you = Guid.NewGuid();
            using (var peer = ZyrePeer.NewPeer(peers, you, ConsoleWrite))
            {
                using (var mailbox = new RouterSocket("tcp://127.0.0.1:5551")) // RouterSocket default action binds to the address
                {
                    peer.Connected.Should().BeFalse();
                    peer.Name = "PeerYou";
                    peer.Name.Should().Be("PeerYou");
                    peer.Connect(me, "tcp://127.0.0.1:5551"); // create a DealerSocket connected to router on 5551
                    peer.Connected.Should().BeTrue();
                    var helloMsg = new ZreMsg
                    {
                        Id = ZreMsg.MessageId.Hello,
                        Hello =
                        {
                            Endpoint = "tcp://127.0.0.1:5552",
                            Name = "PeerMe"
                        },
                    };
                    var success = peer.Send(helloMsg);
                    success.Should().BeTrue();

                    var msg = new ZreMsg();
                    msg.Receive(mailbox);
                    var identityMe = ZyrePeer.GetIdentity(me);
                    var routingEqual = msg.RoutingId.SequenceEqual(identityMe);
                    routingEqual.Should().BeTrue();
                    var hello = msg.Hello;
                    hello.Version.Should().Be(2);
                    hello.Sequence.Should().Be(1);
                    hello.Endpoint.Should().Be("tcp://127.0.0.1:5552");
                    hello.Status.Should().Be(0);
                    hello.Name.Should().Be("PeerMe");
                    hello.Headers.Count.Should().Be(0);
                }
            }
        }
예제 #17
0
        public void Mandatory()
        {
            using (var router = new RouterSocket())
            {
                router.Options.RouterMandatory = true;
                router.Bind("tcp://127.0.0.1:5555");

                using (var dealer = new DealerSocket())
                {
                    dealer.Options.Identity = Encoding.ASCII.GetBytes("1");
                    dealer.Connect("tcp://127.0.0.1:5555");

                    dealer.SendFrame("Hello");

                    Assert.AreEqual("1", router.ReceiveFrameString());
                    Assert.AreEqual("Hello", router.ReceiveFrameString());
                }

                Thread.Sleep(100);

                Assert.Throws<HostUnreachableException>(() => router.SendMoreFrame("1").SendFrame("Hello"));
            }
        }
예제 #18
0
        public void Handover()
        {
            using (var router = new RouterSocket())
            using (var dealer1 = new DealerSocket())
            {
                router.Options.RouterHandover = true;
                router.Bind("inproc://127.0.0.1:5555");
                dealer1.Options.Identity = Encoding.ASCII.GetBytes("ID");
                dealer1.Connect("inproc://127.0.0.1:5555");
                dealer1.SendMoreFrame("Hello").SendFrame("World");

                var identity = router.ReceiveFrameString();
                Assert.AreEqual("ID", identity);

                using (var dealer2 = new DealerSocket())
                {
                    dealer2.Options.Identity = Encoding.ASCII.GetBytes("ID");
                    dealer2.Connect("inproc://127.0.0.1:5555");

                    // We have new peer which should take over, however we are still reading a message
                    var message = router.ReceiveFrameString();
                    Assert.AreEqual("Hello", message);
                    message = router.ReceiveFrameString();
                    Assert.AreEqual("World", message);

                    dealer2.SendMoreFrame("Hello").SendFrame("World");
                    identity = router.ReceiveFrameString();
                    Assert.AreEqual("ID", identity);

                    message = router.ReceiveFrameString();
                    Assert.AreEqual("Hello", message);

                    message = router.ReceiveFrameString();
                    Assert.AreEqual("World", message);
                }
            }
        }
예제 #19
0
파일: SocketTests.cs 프로젝트: hdxhan/netmq
        public void InprocRouterDealerTest()
        {
            // The main thread simply starts several clients and a server, and then
            // waits for the server to finish.
            var readyMsg = Encoding.UTF8.GetBytes("RDY");
            var freeWorkers = new Queue<byte[]>();

            using (var backendsRouter = new RouterSocket())
            {
                backendsRouter.Options.Identity = Guid.NewGuid().ToByteArray();
                backendsRouter.Bind("inproc://backend");

                backendsRouter.ReceiveReady += (o, e) =>
                {
                    // Handle worker activity on backend
                    while (e.Socket.HasIn)
                    {
                        var msg = e.Socket.ReceiveMultipartMessage();
                        var idRouter = msg.Pop();
                        // forget the empty frame
                        if (msg.First.IsEmpty)
                            msg.Pop();

                        var id = msg.Pop();
                        if (msg.First.IsEmpty)
                            msg.Pop();

                        if (msg.FrameCount == 1)
                        {
                            // worker send RDY message queue his Identity to the free workers queue
                            if (readyMsg[0] == msg[0].Buffer[0] &&
                                readyMsg[1] == msg[0].Buffer[1] &&
                                readyMsg[2] == msg[0].Buffer[2])
                            {
                                lock (freeWorkers)
                                {
                                    freeWorkers.Enqueue(id.Buffer);
                                }
                            }
                        }
                    }
                };

                var poller = new NetMQPoller { backendsRouter };

                for (int i = 0; i < 2; i++)
                {
                    var workerThread = new Thread(state =>
                        {
                            byte[] routerId = (byte[])state;
                            byte[] workerId = Guid.NewGuid().ToByteArray();
                            using (var workerSocket = new DealerSocket())
                            {
                                workerSocket.Options.Identity = workerId;
                                workerSocket.Connect("inproc://backend");

                                var workerReadyMsg = new NetMQMessage();
                                workerReadyMsg.Append(workerId);
                                workerReadyMsg.AppendEmptyFrame();
                                workerReadyMsg.Append(readyMsg);
                                workerSocket.SendMultipartMessage(workerReadyMsg);
                                Thread.Sleep(1000);
                            }
                        });
                    workerThread.IsBackground = true;
                    workerThread.Name = "worker" + i;
                    workerThread.Start(backendsRouter.Options.Identity);
                }

                poller.RunAsync();
                Thread.Sleep(1000);
                poller.Stop();
                Assert.AreEqual(2, freeWorkers.Count);
            }
        }
예제 #20
0
파일: SocketTests.cs 프로젝트: hdxhan/netmq
        public void ReconnectOnRouterBug()
        {
            {
                using (var dealer = new DealerSocket())
                {
                    dealer.Options.Identity = Encoding.ASCII.GetBytes("dealer");
                    dealer.Bind("tcp://localhost:6667");

                    using (var router = new RouterSocket())
                    {
                        router.Options.RouterMandatory = true;
                        router.Connect("tcp://localhost:6667");
                        Thread.Sleep(100);

                        router.SendMoreFrame("dealer").SendFrame("Hello");
                        var message = dealer.ReceiveFrameString();
                        Assert.That(message == "Hello");

                        router.Disconnect("tcp://localhost:6667");
                        Thread.Sleep(1000);
                        router.Connect("tcp://localhost:6667");
                        Thread.Sleep(100);

                        router.SendMoreFrame("dealer").SendFrame("Hello");
                        message = dealer.ReceiveFrameString();
                        Assert.That(message == "Hello");
                    }
                }
            }
        }
예제 #21
0
파일: SocketTests.cs 프로젝트: hdxhan/netmq
        public void HasInTest()
        {
            using (var server = new RouterSocket())
            using (var client = new DealerSocket())
            {
                var port = server.BindRandomPort("tcp://*");

                // no one sent a message so it should be false
                Assert.IsFalse(server.HasIn);

                client.Connect("tcp://localhost:" + port);

                // wait for the client to connect
                Thread.Sleep(100);

                // now we have one client connected but didn't send a message yet
                Assert.IsFalse(server.HasIn);

                client.SendFrame("1");

                // wait for the message to arrive
                Thread.Sleep(100);

                // the has in should indicate a message is ready
                Assert.IsTrue(server.HasIn);

                server.SkipFrame(); // identity
                string message = server.ReceiveFrameString();

                Assert.AreEqual(message, "1");

                // we read the message, it should false again
                Assert.IsFalse(server.HasIn);
            }
        }
예제 #22
0
        public void RemoveSocket()
        {
            using (var router1 = new RouterSocket())
            using (var router2 = new RouterSocket())
            using (var router3 = new RouterSocket())
            using (var dealer1 = new DealerSocket())
            using (var dealer2 = new DealerSocket())
            using (var dealer3 = new DealerSocket())
            using (var poller = new NetMQPoller { router1, router2, router3 })
            {
                int port1 = router1.BindRandomPort("tcp://127.0.0.1");
                int port2 = router2.BindRandomPort("tcp://127.0.0.1");
                int port3 = router3.BindRandomPort("tcp://127.0.0.1");

                dealer1.Connect("tcp://127.0.0.1:" + port1);
                dealer2.Connect("tcp://127.0.0.1:" + port2);
                dealer3.Connect("tcp://127.0.0.1:" + port3);

                bool first = true;

                router1.ReceiveReady += (s, e) =>
                {
                    if (!first)
                        Assert.Fail("This should not happen because we cancelled the socket");
                    first = false;

                    // identity
                    e.Socket.SkipFrame();

                    bool more;
                    Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more));
                    Assert.False(more);

                    // cancelling the socket
                    poller.Remove(e.Socket); // remove self
                };

                router2.ReceiveReady += (s, e) =>
                {
                    // identity
                    byte[] identity = e.Socket.ReceiveFrameBytes();

                    // message
                    e.Socket.SkipFrame();

                    e.Socket.SendMoreFrame(identity);
                    e.Socket.SendFrame("2");
                };

                router3.ReceiveReady += (s, e) =>
                {
                    // identity
                    byte[] identity = e.Socket.ReceiveFrameBytes();

                    // message
                    e.Socket.SkipFrame();

                    e.Socket.SendMoreFrame(identity).SendFrame("3");
                };

                Task pollerTask = Task.Factory.StartNew(poller.Run);

                // Send three messages. Only the first will be processed, as then handler removes
                // the socket from the poller.
                dealer1.SendFrame("Hello");
                dealer1.SendFrame("Hello2");
                dealer1.SendFrame("Hello3");

                // making sure the socket defined before the one cancelled still works
                dealer2.SendFrame("1");
                Assert.AreEqual("2", dealer2.ReceiveFrameString());

                // making sure the socket defined after the one cancelled still works
                dealer3.SendFrame("1");
                Assert.AreEqual("3", dealer3.ReceiveFrameString());

                poller.Stop();
                Assert.IsTrue(pollerTask.IsCompleted);
            }
        }
예제 #23
0
파일: SocketTests.cs 프로젝트: hdxhan/netmq
        public void RawSocket()
        {
            using (var router = new RouterSocket())
            using (var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                router.Options.RouterRawSocket = true;
                var port = router.BindRandomPort("tcp://127.0.0.1");

                clientSocket.Connect("127.0.0.1", port);
                clientSocket.NoDelay = true;

                byte[] clientMessage = Encoding.ASCII.GetBytes("HelloRaw");

                int bytesSent = clientSocket.Send(clientMessage);
                Assert.Greater(bytesSent, 0);

                byte[] id = router.ReceiveFrameBytes();
                byte[] message = router.ReceiveFrameBytes();

                router.SendMoreFrame(id).SendMoreFrame(message); // SendMore option is ignored

                var buffer = new byte[16];

                int bytesRead = clientSocket.Receive(buffer);
                Assert.Greater(bytesRead, 0);

                Assert.AreEqual(Encoding.ASCII.GetString(buffer, 0, bytesRead), "HelloRaw");
            }
        }
예제 #24
0
        public void SimpleTimer()
        {
            // TODO it is not really clear what this test is actually testing -- maybe split it into a few smaller tests

            using (var router = new RouterSocket())
            using (var dealer = new DealerSocket())
            using (var poller = new NetMQPoller { router })
            {
                int port = router.BindRandomPort("tcp://127.0.0.1");

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

                bool messageArrived = false;

                router.ReceiveReady += (s, e) =>
                {
                    Assert.IsFalse(messageArrived);
                    router.SkipFrame();
                    router.SkipFrame();
                    messageArrived = true;
                };

                bool timerTriggered = false;

                int count = 0;

                const int timerIntervalMillis = 100;

                var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis));
                timer.Elapsed += (s, a) =>
                {
                    // the timer should jump before the message
                    Assert.IsFalse(messageArrived);
                    timerTriggered = true;
                    timer.Enable = false;
                    count++;
                };
                poller.Add(timer);

                poller.RunAsync();

                Thread.Sleep(150);

                dealer.SendFrame("hello");

                Thread.Sleep(300);

                poller.Stop();

                Assert.IsTrue(messageArrived);
                Assert.IsTrue(timerTriggered);
                Assert.AreEqual(1, count);
            }
        }
예제 #25
0
        public void RemoveTimer()
        {
            using (var router = new RouterSocket())
            using (var dealer = new DealerSocket())
            using (var poller = new NetMQPoller { router })
            {
                int port = router.BindRandomPort("tcp://127.0.0.1");

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

                bool timerTriggered = false;

                var timer = new NetMQTimer(TimeSpan.FromMilliseconds(100));
                timer.Elapsed += (s, a) => { timerTriggered = true; };

                // The timer will fire after 100ms
                poller.Add(timer);

                bool messageArrived = false;

                router.ReceiveReady += (s, e) =>
                {
                    router.SkipFrame();
                    router.SkipFrame();
                    messageArrived = true;
                    // Remove timer
                    poller.Remove(timer);
                };

                poller.RunAsync();

                Thread.Sleep(20);

                dealer.SendFrame("hello");

                Thread.Sleep(300);

                poller.Stop();

                Assert.IsTrue(messageArrived);
                Assert.IsFalse(timerTriggered);
            }
        }
예제 #26
0
        /// <summary>
        /// Release any contained resources.
        /// </summary>
        /// <param name="disposing">true if managed resources are to be released</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
                return;

            if (_outbox != null)
            {
                _outbox.Dispose();
                _outbox = null;
            }
            if (_poller != null)
            {
                _poller.Stop();
                _poller.Dispose();
                _poller = null;
            }
            if (_beacon != null)
            {
                _beacon.Dispose();
                _beacon = null;
            }
            if (_inbox != null)
            {
                _inbox.Dispose();
                _inbox = null;
            }
            foreach (var peer in _peers.Values)
            {
                peer.Destroy();
            }
            foreach (var group in _peerGroups.Values)
            {
                group.Dispose();
            }
            foreach (var group in _ownGroups.Values)
            {
                group.Dispose();
            }
        }
예제 #27
0
        private ZreNode(PairSocket outbox)
        {
            _inbox = new RouterSocket();

            //  Use ZMQ_ROUTER_HANDOVER so that when a peer disconnects and
            //  then reconnects, the new client connection is treated as the
            //  canonical one, and any old trailing commands are discarded.
            // NOTE: This RouterHandover option apparently doesn't exist in NetMQ 
            //      so I IGNORE it for now. DaleBrubaker Feb 1 2016

            _outbox = outbox;
            //_beaconPort = ZreDiscoveryPort;
            _interval = TimeSpan.Zero; // Use default
            _uuid = Guid.NewGuid();
            _peers = new Dictionary<Guid, ZrePeer>();
            _peerGroups = new Dictionary<string, ZreGroup>();
            _ownGroups = new Dictionary<string, ZreGroup>();
            _headers = new Dictionary<string, string>();

            //  Default name for node is first 6 characters of UUID:
            //  the shorter string is more readable in logs
            _name = _uuid.ToString().ToUpper().Substring(0, 6);

            _actor = NetMQActor.Create(RunActor);
        }
		public void Router_Dealer_Demonstrating_Messages_From_Subscribers_To_Publisher()
		{
			// NOTES
			// 1. Use ThreadLocal<DealerSocket> where each thread has
			//    its own client DealerSocket to talk to server
			// 2. Each thread can send using it own socket
			// 3. Each thread socket is added to poller

			const int delay = 500; // millis

			var clientSocketPerThread = new ThreadLocal<DealerSocket>();

			using (var server = new RouterSocket("@tcp://127.0.0.1:5556"))
			{
				using (var poller = new NetMQPoller())
				{
					// Start some threads, each with its own DealerSocket
					// to talk to the server socket. Creates lots of sockets,
					// but no nasty race conditions no shared state, each
					// thread has its own socket, happy days.
					for (int i = 0; i < 4; i++)
					{
						Task.Factory.StartNew(state =>
						{
							DealerSocket client = null;

							if (!clientSocketPerThread.IsValueCreated)
							{
								client = new DealerSocket();
								client.Options.Identity =
									Encoding.Unicode.GetBytes(state.ToString());
								client.Connect("tcp://127.0.0.1:5556");
								client.ReceiveReady += Client_ReceiveReady;
								clientSocketPerThread.Value = client;
								poller.Add(client);
							}
							else
							{
								client = clientSocketPerThread.Value;
							}

							while (true)
							{
								NetMQMessage messageToServer = new NetMQMessage();
								messageToServer.AppendEmptyFrame();
								messageToServer.Append(state.ToString());
								Console.WriteLine("======================================");
								Console.WriteLine(" OUTGOING MESSAGE TO SERVER ");
								Console.WriteLine("======================================");
								PrintFrames("Client Sending", messageToServer);
								client.SendMultipartMessage(messageToServer);
								Thread.Sleep(delay);
							}

						},
							string.Format("client {0}", i),
							TaskCreationOptions.LongRunning);
					}

					// start the poller
					poller.RunAsync();

					// server loop
					for(int i=0;i<6;i++)
					{
						NetMQMessage clientMessage = server.ReceiveMessage();
						Console.WriteLine("======================================");
						Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT ");
						Console.WriteLine("======================================");
						PrintFrames("Server receiving", clientMessage);
						if (clientMessage.FrameCount == 3)
						{
							var clientAddress = clientMessage[0];
							var clientOriginalMessage = clientMessage[2].ConvertToString();
							string response = string.Format("{0} back from server {1}",
								clientOriginalMessage,
								DateTime.Now.ToLongTimeString());
							var messageToClient = new NetMQMessage();
							messageToClient.Append(clientAddress);
							messageToClient.AppendEmptyFrame();
							messageToClient.Append(response);
							server.SendMultipartMessage(messageToClient);
						}
					}
				}
			}
		}
예제 #29
0
        public void AddSocketDuringWork()
        {
            using (var router1 = new RouterSocket())
            using (var router2 = new RouterSocket())
            using (var dealer1 = new DealerSocket())
            using (var dealer2 = new DealerSocket())
            using (var poller = new NetMQPoller { router1 })
            {
                int port1 = router1.BindRandomPort("tcp://127.0.0.1");
                int port2 = router2.BindRandomPort("tcp://127.0.0.1");

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

                bool router1Arrived = false;
                bool router2Arrived = false;

                var signal1 = new ManualResetEvent(false);
                var signal2 = new ManualResetEvent(false);

                router1.ReceiveReady += (s, e) =>
                {
                    router1.SkipFrame();
                    router1.SkipFrame();
                    router1Arrived = true;
                    poller.Add(router2);
                    signal1.Set();
                };

                router2.ReceiveReady += (s, e) =>
                {
                    router2.SkipFrame();
                    router2.SkipFrame();
                    router2Arrived = true;
                    signal2.Set();
                };

                poller.RunAsync();

                dealer1.SendFrame("1");
                Assert.IsTrue(signal1.WaitOne(300));

                dealer2.SendFrame("2");
                Assert.IsTrue(signal2.WaitOne(300));

                poller.Stop();

                Assert.IsTrue(router1Arrived);
                Assert.IsTrue(router2Arrived);
            }
        }
예제 #30
0
        public void RequestResponseMultipartMessageWithRetrySucceedsNotOnFirstTry()
        {
            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 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.RequestResponseMultipartMessageWithRetry(address,
                        requestMessage, numTries, requestTimeout, progressPublisher);
                    Assert.IsNotNull(responseMessage);
                    Assert.AreEqual(1, responseMessage.FrameCount);
                    var responseString = responseMessage.First.ConvertToString();
                    Assert.AreEqual("Hi", responseString);
                }
            }
        }