예제 #1
0
파일: Zyre.cs 프로젝트: NetMQ/Zyre
        /// <summary>
        /// Create a Zyre API that communicates with a node on the ZRE bus.
        /// </summary>
        /// <param name="name">The name of the node</param>
        /// <param name="useEvents">Set this to true to disable Receive() and instead subscribe to events for getting messages from peers. Default is true.</param>
        /// <param name="loggerDelegate">An action to take for logging when _verbose is true. Default is null.</param>
        public Zyre (string name, bool useEvents = true, Action<string> loggerDelegate = null)
        {
            _useEvents = useEvents;
            // Create front-to-back pipe pair for data traffic
            // outbox is passed to ZyreNode for sending Zyre message traffic back to _inbox
            PairSocket outbox;
            PairSocket.CreateSocketPair(out outbox, out _inbox);

            // Start node engine and wait for it to be ready
            // All node control is done through _actor

            _actor = ZyreNode.Create(outbox, loggerDelegate);

            if (useEvents)
            {
                _inboxPoller = new NetMQPoller();
                _inbox.ReceiveReady += InboxReceiveReady;
                _inboxPoller.RunAsync();
            }

            // Send name, if any, to node ending
            if (!string.IsNullOrEmpty(name))
            {
                _actor.SendMoreFrame("SET NAME").SendFrame(name);
            }
        }
예제 #2
0
        public void ResponsePoll()
        {
            using (var rep = new ResponseSocket())
            using (var req = new RequestSocket())
            using (var poller = new NetMQPoller { rep })
            {
                int port = rep.BindRandomPort("tcp://127.0.0.1");

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

                rep.ReceiveReady += (s, e) =>
                {
                    bool more;
                    Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more));
                    Assert.False(more);

                    e.Socket.SendFrame("World");
                };

                poller.RunAsync();

                req.SendFrame("Hello");

                bool more2;
                Assert.AreEqual("World", req.ReceiveFrameString(out more2));
                Assert.IsFalse(more2);

                poller.Stop();
            }
        }
예제 #3
0
        void IShimHandler.Run(PairSocket shim)
        {
            Poller = new NetMQPoller();


            Shim = shim;
            Shim.ReceiveReady += OnShimReady;
            Poller.Add(Shim);

            Initialize();

            Shim.SignalOK();

            Poller.Run();

            Cleanup();
        }
예제 #4
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();
            }
        }
예제 #5
0
        public void WithPoller()
        {
            using (var queue = new NetMQQueue<int>())
            using (var poller = new NetMQPoller { queue })
            {
                var manualResetEvent = new ManualResetEvent(false);

                queue.ReceiveReady += (sender, args) =>
                {
                    Assert.AreEqual(1, queue.Dequeue());
                    manualResetEvent.Set();
                };

                poller.RunAsync();

                Assert.IsFalse(manualResetEvent.WaitOne(100));
                queue.Enqueue(1);
                Assert.IsTrue(manualResetEvent.WaitOne(100));
            }
        }
예제 #6
0
        public void Monitoring()
        {
            var listeningEvent = new ManualResetEvent(false);
            var acceptedEvent = new ManualResetEvent(false);
            var connectedEvent = new ManualResetEvent(false);

            using (var rep = new ResponseSocket())
            using (var req = new RequestSocket())
            using (var poller = new NetMQPoller())
            using (var repMonitor = new NetMQMonitor(rep, "inproc://rep.inproc", SocketEvents.Accepted | SocketEvents.Listening))
            using (var reqMonitor = new NetMQMonitor(req, "inproc://req.inproc", SocketEvents.Connected))
            {
                repMonitor.Accepted += (s, e) => acceptedEvent.Set();
                repMonitor.Listening += (s, e) => listeningEvent.Set();

                repMonitor.AttachToPoller(poller);

                int port = rep.BindRandomPort("tcp://127.0.0.1");

                reqMonitor.Connected += (s, e) => connectedEvent.Set();

                reqMonitor.AttachToPoller(poller);

                poller.RunAsync();

                req.Connect("tcp://127.0.0.1:" + port);
                req.SendFrame("a");

                rep.SkipFrame();

                rep.SendFrame("b");

                req.SkipFrame();

                Assert.IsTrue(listeningEvent.WaitOne(300));
                Assert.IsTrue(connectedEvent.WaitOne(300));
                Assert.IsTrue(acceptedEvent.WaitOne(300));

                poller.Stop();
            }
        }
예제 #7
0
        //Provide People to the client
        public static void ProvidePeople()
        {
            using (var server = new ResponseSocket(Config.URL))
                using (var poller = new NetMQPoller {
                    server
                })
                {
                    var reader = new Reader();

                    server.ReceiveReady += (sender, e) =>
                    {
                        var command = e.Socket.ReceiveFrameString();

                        switch (command.ToLower())
                        {
                        case "getpeople":

                            List <IPerson> people = reader.ReadData(Config.DATA_FILE_PATH);

                            var message = new NetMQMessage(people.Count - 1);

                            people.ForEach(p => message.Append(p.ToString()));

                            e.Socket.SendMultipartMessage(message);

                            break;

                        default:
                            e.Socket.SendFrame(String.Format(Config.DEFAULT_SERVICE_MESSAGE, command));

                            break;
                        }

                        Console.Read();
                    };

                    poller.Run();
                    Console.Read();
                }
        }
예제 #8
0
        public void TwoTimers()
        {
            var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(52));
            var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(40));

            int count  = 0;
            int count2 = 0;

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

            timer1.Elapsed += (s, a) =>
            {
                count++;
                timer1.Enable = false;
                timer2.Enable = false;
                signal1.Set();
            };

            timer2.Elapsed += (s, e) =>
            {
                count2++;
                signal2.Set();
            };

            using (var poller = new NetMQPoller {
                timer1, timer2
            })
            {
                poller.RunAsync();

                Assert.IsTrue(signal1.WaitOne(300));
                Assert.IsTrue(signal2.WaitOne(300));

                poller.Stop();
            }

            Assert.AreEqual(1, count);
            Assert.AreEqual(1, count2);
        }
예제 #9
0
 private void StratListen(int milliseconds = NetmqOptions.PolicyMillisecond)
 {
     Task.Factory.StartNew((par) =>
     {
         var listen            = par as List <PublisherListen>;
         NetMQTimer netMQTimer = new NetMQTimer(milliseconds);
         netMQTimer.Elapsed   += (a, b) =>
         {
             foreach (var item in listen)
             {
                 //检测发送的命令是否收到客户端回复 没有则持续发送出去
                 if (item.IsSendListens())
                 {
                     Publish(item.Topic, item.SendData);
                 }
                 else
                 {
                     //检测客户端是否断网 down 机了
                     if (item.IsListensServiceError())
                     {
                         var objdata = item.SendData as CommandDto;
                         OnResponseReceivePushEvent(new LogDto()
                         {
                             LogType = LiveStateType.ServiceError, ChanneId = objdata.ChanneId
                         });
                         item.SendWebClientDate = DateTime.Now;
                     }
                 }
             }
             ChannelOperation();
         };
         using (var poller = new NetMQPoller()
         {
             netMQTimer
         })
         {
             poller.Run();
         }
     }, _publisherListens);
 }
예제 #10
0
        public void ISynchronizeInvokeWorks()
        {
            using (var poller = new NetMQPoller())
                using (var signal = new ManualResetEvent(false))
                    using (var timer = new System.Timers.Timer {
                        AutoReset = false, Interval = 100, SynchronizingObject = poller, Enabled = true
                    })
                    {
                        var isCorrectThread = false;

                        poller.RunAsync();

                        timer.Elapsed += (sender, args) =>
                        {
                            isCorrectThread = poller.CanExecuteTaskInline;
                            Assert.True(signal.Set());
                        };

                        Assert.True(signal.WaitOne(TimeSpan.FromSeconds(2)));
                        Assert.True(isCorrectThread);
                    }
        }
예제 #11
0
        public void WithPoller()
        {
            using (var queue = new NetMQQueue <int>())
                using (var poller = new NetMQPoller {
                    queue
                })
                {
                    var manualResetEvent = new ManualResetEvent(false);

                    queue.ReceiveReady += (sender, args) =>
                    {
                        Assert.AreEqual(1, queue.Dequeue());
                        manualResetEvent.Set();
                    };

                    poller.RunAsync();

                    Assert.IsFalse(manualResetEvent.WaitOne(100));
                    queue.Enqueue(1);
                    Assert.IsTrue(manualResetEvent.WaitOne(100));
                }
        }
예제 #12
0
        /// <summary>
        ///     Stops the server.
        /// </summary>
        public void StopServer()
        {
            if (!ServerRunning)
            {
                return;
            }

            _poller?.Stop();
            _poller?.Dispose();

            lock (_publisherSocketLock) {
                if (_publisherSocket != null)
                {
                    try {
                        _publisherSocket.Disconnect(_publisherConnectionString);
                    }
                    finally {
                        _publisherSocket.Close();
                        _publisherSocket = null;
                    }
                }
            }

            lock (_requestSocketLock) {
                if (_requestSocket != null)
                {
                    try {
                        _requestSocket.Disconnect(_requestConnectionString);
                    }
                    finally {
                        _requestSocket.ReceiveReady -= RequestSocketReceiveReady;
                        _requestSocket.Close();
                        _requestSocket = null;
                    }
                }
            }

            _poller = null;
        }
예제 #13
0
        /// <summary>
        /// This method is being run asynchronously by m_actor.
        /// </summary>
        /// <param name="shim"></param>
        private void RunActor(PairSocket shim)
        {
            _pipe = shim;
            _pipe.ReceiveReady += OnPipeReceiveReady;

            var reapTimer = new NetMQTimer(TimeSpan.FromMilliseconds(1000));

            reapTimer.Elapsed += OnReapTimerElapsed;

            // Start poller, but poll only the _pipe. Start() and Stop() will add/remove other items to poll
            _poller = new NetMQPoller {
                _pipe, reapTimer
            };

            // Signal the actor that we're ready to work
            _pipe.SignalOK();

            // polling until cancelled
            _poller.Run();

            Dispose();
        }
예제 #14
0
        public void RemoveThrowsIfSocketAlreadyDisposed()
        {
            var socket = new RouterSocket();

            var poller = new NetMQPoller {
                socket
            };

            // Dispose the socket.
            // It is incorrect to have a disposed socket in a poller.
            // Disposed sockets can throw into the poller's thread.
            socket.Dispose();

            // Remove throws if the removed socket
            var ex = Assert.Throws <ArgumentException>(() => poller.Remove(socket));

            Assert.True(ex.Message.StartsWith("Must not be disposed."));
            Assert.AreEqual("socket", ex.ParamName);

            // Still dispose it. It throws after cleanup.
            Assert.Throws <NetMQException>(() => poller.Dispose());
        }
예제 #15
0
        public void Run(PairSocket shim)
        {
            string shimAdd = $"inproc://wsrouter-{Id}";

            Monitor.Enter(this);
            try
            {
                isRuning = true;
                shim.SignalOK();

                shim.ReceiveReady += OnShimReady;

                MessagesPipe = new PairSocket();
                MessagesPipe.Connect(shimAdd);
                MessagesPipe.ReceiveReady += OnMessagePipeReady;

                Stream = new StreamSocket();
                Stream.Bind(Address);
                Stream.ReceiveReady += OnStreamReady;

                Poller = new NetMQPoller
                {
                    MessagesPipe,
                    shim,
                    Stream
                };
                MessagesPipe.SignalOK();
                Poller.Run();
                shim.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Monitor.Exit(this);
            }
        }
예제 #16
0
        public void TwoThreads()
        {
            int count1 = 0;
            int count2 = 0;

            var allTasks = new ConcurrentBag <Task>();

            using (var poller = new NetMQPoller())
            {
                poller.RunAsync();

                Task t1 = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        var task = new Task(() => { count1++; });
                        allTasks.Add(task);
                        task.Start(poller);
                    }
                });

                Task t2 = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        var task = new Task(() => { count2++; });
                        allTasks.Add(task);
                        task.Start(poller);
                    }
                });

                t1.Wait(1000);
                t2.Wait(1000);
                Task.WaitAll(allTasks.ToArray(), 1000);

                Assert.AreEqual(100, count1);
                Assert.AreEqual(100, count2);
            }
        }
예제 #17
0
        protected void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _proxy.Stop();
                    _proxy = null;

                    _poller.Dispose();
                    _poller = null;

                    _backendSocket.Dispose();
                    _backendSocket = null;

                    _frontendSocket.Dispose();
                    _frontendSocket = null;
                }

                _disposedValue = true;
            }
        }
예제 #18
0
        public void Stop()
        {
            if (!IsRunning)
            {
                return;
            }

            this._nodes.Clear();

            _poller.Stop();
            _beacon.Unsubscribe();
            _poller.Remove(_beacon);
            _poller.Remove(timer);

            _poller.Dispose();
            _poller = null;

            _beacon.Dispose();
            _beacon = null;

            timer = null;
        }
예제 #19
0
        // Use this for initialization
        void Start()
        {
            //set-up socket and poller
            SceneClient = new SubscriberSocket();
            SceneClient.Subscribe("vision-mode");//vision-update, but "any" for testing
            UnityEngine.Debug.Log("set up the subscription at " + server_uri);
            SceneClient.Connect(server_uri);
            ScenePoller = new NetMQPoller {
                SceneClient
            };
            //set-up event to add to task
            SceneResponseTask         = new TaskCompletionSource <string>();
            SceneClient.ReceiveReady += (s, a) =>
            {
                List <string> msg = a.Socket.ReceiveMultipartStrings();

                SceneResponseTask.TrySetResult(msg[1]);
            };

            //start polling thread
            ScenePoller.RunAsync();
        }
예제 #20
0
        public void TestProxySendAndReceiveWithExternalPoller()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                    using (var poller = new NetMQPoller {
                        front, back
                    })
                    {
                        front.Bind("inproc://frontend");
                        back.Bind("inproc://backend");

                        var proxy = new Proxy(front, back, null, poller);

                        poller.RunAsync();

                        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());

                                // Now stop the external poller
                                poller.Stop();

                                client.SendFrame("anyone there?");

                                // Should no longer receive any messages
                                Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50)));
                            }
                    }
        }
예제 #21
0
        public void CycleCreateTerminate()
        {
            NetMQConfig.ContextCreate(true);
            var isTerminated = VerifyTermination();
            Assert.AreEqual(false, isTerminated);

            // We use the Poller Test code.
            using (var rep = new ResponseSocket())
            using (var req = new RequestSocket())
            using (var poller = new NetMQPoller { rep })
            {
                var port = rep.BindRandomPort("tcp://127.0.0.1");

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

                rep.ReceiveReady += (s, e) =>
                {
                    bool more;
                    Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more));
                    Assert.False(more);

                    e.Socket.SendFrame("World");
                };

                poller.RunAsync();

                req.SendFrame("Hello");

                bool more2;
                Assert.AreEqual("World", req.ReceiveFrameString(out more2));
                Assert.IsFalse(more2);

                poller.Stop();
            }
            NetMQConfig.ContextTerminate();
            isTerminated = VerifyTermination();
            Assert.AreEqual(true, isTerminated);
        }
예제 #22
0
        public void Polling()
        {
            using (var speaker = new NetMQBeacon())
                using (var listener = new NetMQBeacon())
                {
                    speaker.Configure(9999);
                    Console.WriteLine(speaker.Hostname);

                    speaker.Publish("Hello", s_publishInterval);

                    var manualResetEvent = new ManualResetEvent(false);

                    listener.Configure(9999);
                    listener.Subscribe("H");

                    string peerName = "";
                    string message  = "";

                    listener.ReceiveReady += (sender, args) =>
                    {
                        message = listener.ReceiveString(out peerName);
                        manualResetEvent.Set();
                    };

                    using (var poller = new NetMQPoller {
                        listener
                    })
                    {
                        poller.RunAsync();

                        manualResetEvent.WaitOne();

                        Console.WriteLine(peerName);

                        Assert.AreEqual("Hello", message);
                    }
                }
        }
예제 #23
0
        public void StoppingProxyDisengagesFunctionality()
        {
            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);

                    // Send a message through to ensure the proxy has started
                    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(); // blocks until stopped

                            using (var poller = new NetMQPoller {
                                front, back
                            })
                            {
                                poller.RunAsync();

                                client.SendFrame("anyone there?");

                                // Should no longer receive any messages
                                Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50)));
                            }
                        }
                }
        }
예제 #24
0
        /// <summary>
        ///     run the broker - if not bound to endpoint automatically binds to known endpoint
        /// </summary>
        /// <param name="token">CancellationToken to cancel the method</param>
        /// <exception cref="InvalidOperationException">Can't start same broker more than once!</exception>
        public void RunSynchronous (CancellationToken token)
        {
            if (m_isRunning)
                throw new InvalidOperationException ("Can't start same broker more than once!");

            if (!m_isBound)
                Bind ();

            m_isRunning = true;

            using (var poller = new NetMQPoller ())
            {
                Socket.ReceiveReady += ProcessReceivedMessage;
                // get timer for scheduling heartbeat
                var timer = new NetMQTimer (HeartbeatInterval);
                // send every 'HeartbeatInterval' a heartbeat to all not expired workers
                timer.Elapsed += (s, e) => SendHeartbeat ();

                poller.Add (Socket);
                poller.Add (timer);

                Log ("Starting to listen for incoming messages ...");

                // start the poller and wait for the return, which will happen once token is
                // signalling Cancel(!)
                Task.Factory.StartNew (poller.Run, token).Wait ();

                Log ("... Stopped!");

                // clean up
                poller.Remove (timer);
                poller.Remove (Socket);
                // unregister event handler
                Socket.ReceiveReady -= ProcessReceivedMessage;
            }

            m_isRunning = false;
        }
예제 #25
0
        public void ResponseReceive(int Milliseconds = NetmqOptions.ResopneMillisecond)
        {
            Task.Factory.StartNew((par) =>
            {
                try
                {
                    var listen      = par as List <PublisherListen>;
                    var isCancel    = cancellationTokenSource.Token.IsCancellationRequested;
                    var mqTime      = new NetMQTimer(TimeSpan.FromMilliseconds(Milliseconds));
                    mqTime.Elapsed += (sender, e) =>
                    {
                        if (isCancel)
                        {
                            e.Timer.Enable = false;
                            return;
                        }

                        _netMQManage.ResponseReceive((a) =>
                        {
                            //收到消息后进行回调处理业务,处理完后在 反馈消息出去
                            var request = JsonConvert.DeserializeObject <RequestData>(a);
                            listen.ResultListens(request.Id);
                            return(ResultResponse(request));
                        });
                    };
                    using (var poller = new NetMQPoller {
                        mqTime
                    })
                    {
                        poller.Run();
                    }
                }
                catch (Exception ex)
                {
                    LogWrite.Error(ex);
                }
            }, _publisherListens, cancellationTokenSource.Token);
        }
        /// <summary>
        ///     Starts the server.
        /// </summary>
        public void StartServer()
        {
            if (ServerRunning)
            {
                return;
            }

            //lock (publisherSocketLock)
            //{
            //    publisherSocket = new PushSocket(publisherConnectionString);
            //}

            lock (pullSocketLock)
            {
                pullSocket = new PullSocket(pullSocketConnectionString);
                pullSocket.ReceiveReady += PullSocketReceiveReady;
                logger.Log(LogLevel.Info, $"Pull socket established on {pullSocketConnectionString}");
                poller = new NetMQPoller {
                    pullSocket
                };
                poller.RunAsync();
            }
        }
예제 #27
0
        public Node()
        {
            poller = new NetMQPoller();

            //Create node input
            sub = new SubscriberSocket();

            sub.ReceiveReady += (s, a) =>
            {
                Console.WriteLine("First: " + a.Socket.ReceiveMultipartMessage()[0].ConvertToString());
            };
            poller.Add(sub);
            poller.RunAsync();

            //Create plug output
            pub = new PublisherSocket("@inproc://publisher");
            //Connect plug out to node in

            sub.Connect("inproc://publisher");
            sub.Subscribe("32abd/node0974/out0");

            //Start poller
        }
예제 #28
0
        private void Run(PairSocket shim)
        {
            _shim              = shim;
            shim.ReceiveReady += OnShimMessage;

            _timeoutTimer          = new NetMQTimer(_heartbeatTimeOut);
            _timeoutTimer.Elapsed += OnTimeoutTimer;

            _reconnectTimer          = new NetMQTimer(_reconnectInterval);
            _reconnectTimer.Elapsed += OnReconnectTimer;

            _poller = new NetMQPoller {
                shim, _timeoutTimer, _reconnectTimer
            };

            shim.SignalOK();

            Connect();

            _poller.Run();

            _subscriber?.Dispose();
        }
예제 #29
0
        /// <summary>
        ///     Starts the server.
        /// </summary>
        public void StartServer()
        {
            if (ServerRunning)
            {
                return;
            }

            lock (_publisherSocketLock)
            {
                _publisherSocket = new PublisherSocket(_publisherConnectionString);
            }

            lock (_requestSocketLock)
            {
                _requestSocket = new ResponseSocket(_requestConnectionString);
                _requestSocket.ReceiveReady += RequestSocketReceiveReady;
            }

            _poller = new NetMQPoller {
                _requestSocket
            };
            _poller.RunAsync();
        }
예제 #30
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);
                            }
                    }
        }
예제 #31
0
        public void TerminateAfterSocketsUse()
        {
            NetMQConfig.ContextCreate(true);
            using (var rep = new ResponseSocket())
                using (var req = new RequestSocket())
                    using (var poller = new NetMQPoller {
                        rep
                    })
                    {
                        var port = rep.BindRandomPort("tcp://127.0.0.1");

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

                        rep.ReceiveReady += (s, e) =>
                        {
                            bool more;
                            Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more));
                            Assert.False(more);

                            e.Socket.SendFrame("World");
                        };

                        poller.RunAsync();

                        req.SendFrame("Hello");

                        bool more2;
                        Assert.AreEqual("World", req.ReceiveFrameString(out more2));
                        Assert.IsFalse(more2);

                        poller.Stop();
                    }
            NetMQConfig.ContextTerminate();
            var isTerminated = VerifyTermination();

            Assert.AreEqual(true, isTerminated);
        }
예제 #32
0
 static Task <long> ServerTask(ResponseSocket srv, CancellationToken ctoken)
 {
     return(Task.Run(() =>
     {
         using (var poller = new NetMQPoller())
             using (ctoken.Register(() => poller.StopAsync()))
             {
                 srv.ReceiveReady += (sender, e) =>
                 {
                     var msg = e.Socket.ReceiveFrameBytes();
                     var recvvalue = bytestoi64(msg);
                     // while (!ctoken.IsCancellationRequested)
                     // {
                     //     var old = Interlocked.CompareExchange(ref ret, ret + recvvalue, ret);
                     //     if (old < ret)
                     //     {
                     //         break;
                     //     }
                     // }
                     // Console.WriteLine($"recv {msg}");
                     e.Socket.SendFrame("");
                     // e.Socket.SendFrame("OK", true);
                     // e.Socket.SendFrame("mogemoge", false);
                 };
                 poller.Add(srv);
                 try
                 {
                     poller.Run();
                 }
                 catch (Exception e)
                 {
                     Console.WriteLine($"srv ex={e}");
                 }
             }
         return 0L;
     }));
 }
예제 #33
0
        public void TestReceiveFromLogOverInproc()
        {
            int  processed = 0;
            bool done      = false;

            using (var subcription1 = new SubscriberSocket(InprocAddress))
                using (var poller = new NetMQPoller {
                    subcription1
                })
                {
                    subcription1.SubscribeToAnyTopic();
                    subcription1.ReceiveReady += (s, a) =>
                    {
                        var msg = a.Socket.ReceiveMultipartStrings(2);
                        Assert.AreEqual(2, msg.Count);
                        processed++;
                        if (processed == 3)
                        {
                            done = true;
                            poller.Stop();
                        }
                    };

                    poller.RunAsync();

                    inProcLog.Information("First");
                    inProcLog.Warning("Second");
                    inProcLog.Error("Third");

                    while (!done)
                    {
                        Thread.Sleep(50);
                    }

                    Assert.AreEqual(3, processed);
                }
        }
예제 #34
0
        private void DoWork()
        {
            try
            {
                _poller = new NetMQPoller();

                using (_frontendSocket = new RouterSocket(_frontEndAddress))
                    using (_backendSocket = new DealerSocket(_backEndAddress))
                    {
                        _backendSocket.ReceiveReady  += OnBackEndReady;
                        _frontendSocket.ReceiveReady += OnFrontEndReady;

                        _poller.Add(_backendSocket);
                        _poller.Add(_frontendSocket);

                        _semaphoreStart.Set();

                        _poller.Run();
                    }
            }
            catch (Exception ex)
            {
            }
        }
예제 #35
0
        public void zmqBeginListen(object data)
        {
            Subscriber = new SubscriberSocket();

            ZMQAddress = "tcp://" + Ip + ":3000";
            Console.WriteLine("I: Connecting to {0}...", ZMQAddress);
            Subscriber.Connect(ZMQAddress);

            Subscriber.Subscribe("telemetry");

            var poller = new NetMQPoller {
                Subscriber
            };

            Subscriber.ReceiveReady += (s, a) =>
            {
                if (rPodNetworking.Paused)
                {
                    return;
                }
                NetworkNode.NodeZMQSeen();
                byte[] reply = a.Socket.ReceiveFrameBytes();

                int i = 10;
                while (i < reply.Length && reply[i] != 0xd5)
                {
                    i++;
                }
                rPodNetworking.ProcessZMQTelemetryFrame(reply.Skip(i).ToArray(), NetworkNode.NodeNameShort);
            };
            try
            {
                poller.Run();
            }
            catch { Console.WriteLine("Problem with subscriber running, possibly a node that changed or went offline (?)"); }
        }
예제 #36
0
        public void TestPollerDispose()
        {
            const int timerIntervalMillis = 10;

            var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis));

            var signal = new ManualResetEvent(false);

            var count = 0;

            timer.Elapsed += (s, a) =>
            {
                if (count++ == 5)
                {
                    signal.Set();
                }
            };

            NetMQPoller poller;

            using (poller = new NetMQPoller {
                timer
            })
            {
                poller.RunAsync();
                Assert.IsTrue(signal.WaitOne(500));
                Assert.IsTrue(poller.IsRunning);
                Assert.Throws <InvalidOperationException>(() => poller.Run());
            }

            Assert.IsFalse(poller.IsRunning);
            Assert.Throws <ObjectDisposedException>(() => poller.Run());
            Assert.Throws <ObjectDisposedException>(() => poller.Stop());
            Assert.Throws <ObjectDisposedException>(() => poller.Add(timer));
            Assert.Throws <ObjectDisposedException>(() => poller.Remove(timer));
        }
예제 #37
0
        private void Run(PairSocket shim)
        {
            using (_publisherSocket = new XPublisherSocket())
            {
                _publisherSocket.SetWelcomeMessage(WelcomeMessage);
                _publisherSocket.Bind(_address);

                _publisherSocket.ReceiveReady += DropPublisherSubscriptions;

                _heartbeatTimer          = new NetMQTimer(_heartbeatInterval);
                _heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;

                shim.ReceiveReady += OnShimMessage;

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

                _poller = new NetMQPoller {
                    _publisherSocket, shim, _heartbeatTimer
                };
                // Polling until poller is cancelled
                _poller.Run();
            }
        }
예제 #38
0
        public void CanExecuteTaskInline()
        {
            using (var poller = new NetMQPoller())
            {
                Assert.IsFalse(poller.CanExecuteTaskInline);

                poller.RunAsync();

                Assert.IsFalse(poller.CanExecuteTaskInline);

                var task = new Task(() => Assert.IsTrue(poller.CanExecuteTaskInline));
                task.Start(poller);
                task.Wait();
            }
        }
예제 #39
0
파일: ProxyTests.cs 프로젝트: GrabCAD/netmq
        public void TestProxySendAndReceiveWithExternalPoller()
        {
            using (var front = new RouterSocket())
            using (var back = new DealerSocket())
            using (var poller = new NetMQPoller { front, back })
            {
                front.Bind("inproc://frontend");
                back.Bind("inproc://backend");

                var proxy = new Proxy(front, back, null, poller);
                proxy.Start();

                poller.RunAsync();
                
                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());

                    // Now stop the external poller
                    poller.Stop();

                    client.SendFrame("anyone there?");

                    // Should no longer receive any messages
                    Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50)));
                }
            }
        }
예제 #40
0
        public void AddTwoSocketAfterRemoving()
        {
            using (var router1 = new RouterSocket())
            using (var router2 = new RouterSocket())
            using (var router3 = new RouterSocket())
            using (var router4 = new RouterSocket())
            using (var dealer1 = new DealerSocket())
            using (var dealer2 = new DealerSocket())
            using (var dealer3 = new DealerSocket())
            using (var dealer4 = new DealerSocket())
            using (var poller = new NetMQPoller { router1, router2 })
            {
                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");
                int port4 = router4.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);
                dealer4.Connect("tcp://127.0.0.1:" + port4);

                int router1Arrived = 0;
                int router2Arrived = 0;
                bool router3Arrived = false;
                bool router4Arrived = false;

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

                router1.ReceiveReady += (s, e) =>
                {
                    router1Arrived++;
                    router1.SkipFrame(); // identity
                    router1.SkipFrame(); // message
                    poller.Remove(router1);
                    signal1.Set();
                };

                router2.ReceiveReady += (s, e) =>
                {
                    router2Arrived++;
                    router2.SkipFrame(); // identity
                    router2.SkipFrame(); // message

                    if (router2Arrived == 1)
                    {
                        poller.Add(router3);
                        poller.Add(router4);
                        signal2.Set();
                    }
                };

                router3.ReceiveReady += (s, e) =>
                {
                    router3.SkipFrame(); // identity
                    router3.SkipFrame(); // message
                    router3Arrived = true;
                    signal3.Set();
                };

                router4.ReceiveReady += (s, e) =>
                {
                    router4.SkipFrame(); // identity
                    router4.SkipFrame(); // message
                    router4Arrived = true;
                    signal4.Set();
                };

                poller.RunAsync();

                dealer1.SendFrame("1");
                Assert.IsTrue(signal1.WaitOne(300));
                dealer2.SendFrame("2");
                Assert.IsTrue(signal2.WaitOne(300));
                dealer3.SendFrame("3");
                dealer4.SendFrame("4");
                dealer2.SendFrame("2");
                dealer1.SendFrame("1");
                Assert.IsTrue(signal3.WaitOne(300));
                Assert.IsTrue(signal4.WaitOne(300));

                poller.Stop();

                router1.SkipFrame();
                bool more;
                Assert.AreEqual("1", router1.ReceiveFrameString(out more));
                Assert.IsFalse(more);

                Assert.AreEqual(1, router1Arrived);
                Assert.AreEqual(2, router2Arrived);
                Assert.IsTrue(router3Arrived);
                Assert.IsTrue(router4Arrived);
            }
        }
예제 #41
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);
            }
        }
예제 #42
0
        public void TwoTimers()
        {
            var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(52));
            var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(40));

            int count = 0;
            int count2 = 0;

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

            timer1.Elapsed += (s, a) =>
            {
                count++;
                timer1.Enable = false;
                timer2.Enable = false;
                signal1.Set();
            };

            timer2.Elapsed += (s, e) =>
            {
                count2++;
                signal2.Set();
            };

            using (var poller = new NetMQPoller { timer1, timer2 })
            {
                poller.RunAsync();

                Assert.IsTrue(signal1.WaitOne(300));
                Assert.IsTrue(signal2.WaitOne(300));

                poller.Stop();
            }

            Assert.AreEqual(1, count);
            Assert.AreEqual(1, count2);
        }
예제 #43
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);
            }
        }
예제 #44
0
        public void EnableTimer()
        {
            const int timerIntervalMillis = 20;

            var timer1 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis));
            var timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis)) { Enable = false};

            int count = 0;
            int count2 = 0;

            timer1.Elapsed += (s, a) =>
            {
                count++;

                if (count == 1)
                {
                    timer2.Enable = true;
                    timer1.Enable = false;
                }
                else if (count == 2)
                {
                    timer1.Enable = false;
                }
            };

            timer2.Elapsed += (s, e) =>
            {
                timer1.Enable = true;
                timer2.Enable = false;

                count2++;
            };

            using (var poller = new NetMQPoller { timer1, timer2 })
            {
                poller.RunAsync();

                Thread.Sleep(timerIntervalMillis * 6);

                poller.Stop();
            }

            Assert.AreEqual(2, count);
            Assert.AreEqual(1, count2);
        }
예제 #45
0
        /// <summary>
        /// This method is being run asynchronously by m_actor.
        /// </summary>
        /// <param name="shim"></param>
        private void RunActor(PairSocket shim)
        {
            _pipe = shim;
            _pipe.ReceiveReady += OnPipeReceiveReady;

            var reapTimer = new NetMQTimer(TimeSpan.FromMilliseconds(1000));
            reapTimer.Elapsed += OnReapTimerElapsed;

            // Start poller, but poll only the _pipe. Start() and Stop() will add/remove other items to poll
            _poller = new NetMQPoller { _pipe, reapTimer };

            // Signal the actor that we're ready to work
            _pipe.SignalOK();

            // polling until cancelled
            _poller.Run();

            reapTimer.Enable = false;
            reapTimer.Elapsed -= OnReapTimerElapsed;
        }
예제 #46
0
        public void ChangeTimerInterval()
        {
            int count = 0;

            const int timerIntervalMillis = 10;

            var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis));

            var stopwatch = new Stopwatch();

            long length1 = 0;
            long length2 = 0;

            timer.Elapsed += (s, a) =>
            {
                count++;

                if (count == 1)
                {
                    stopwatch.Start();
                }
                else if (count == 2)
                {
                    length1 = stopwatch.ElapsedMilliseconds;

                    timer.Interval = 20;
                    stopwatch.Restart();
                }
                else if (count == 3)
                {
                    length2 = stopwatch.ElapsedMilliseconds;

                    stopwatch.Stop();

                    timer.Enable = false;
                }
            };

            using (var poller = new NetMQPoller { timer })
            {
                poller.RunAsync();

                Thread.Sleep(timerIntervalMillis * 6);

                poller.Stop();
            }

            Assert.AreEqual(3, count);

            Assert.AreEqual(10.0, length1, 2.0);
            Assert.AreEqual(20.0, length2, 2.0);
        }
예제 #47
0
        public void SetsCurrentTaskScheduler()
        {
            using (var poller = new NetMQPoller())
            {
                poller.RunAsync();

                var task = new Task(() => Assert.AreSame(TaskScheduler.Current, poller));
                task.Start(poller);
                task.Wait();
            }
        }
예제 #48
0
        public void OneTask()
        {
            bool triggered = false;

            using (var poller = new NetMQPoller())
            {
                poller.RunAsync();

                var task = new Task(() =>
                {
                    triggered = true;
                    Assert.IsTrue(poller.CanExecuteTaskInline, "Should be on NetMQPoller thread");
                });
                task.Start(poller);
                task.Wait();

                Assert.IsTrue(triggered);
            }
        }
예제 #49
0
        public void NativeSocket()
        {
            using (var streamServer = new StreamSocket())
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                int port = streamServer.BindRandomPort("tcp://*");

                socket.Connect("127.0.0.1", port);

                var buffer = new byte[] { 1 };
                socket.Send(buffer);

                byte[] identity = streamServer.ReceiveFrameBytes();
                byte[] message = streamServer.ReceiveFrameBytes();

                Assert.AreEqual(buffer[0], message[0]);

                var socketSignal = new ManualResetEvent(false);

                using (var poller = new NetMQPoller())
                {
                    poller.Add(socket, s =>
                    {
                        socket.Receive(buffer);

                        socketSignal.Set();

                        // removing the socket
                        poller.Remove(socket);
                    });

                    poller.RunAsync();

                    // no message is waiting for the socket so it should fail
                    Assert.IsFalse(socketSignal.WaitOne(100));

                    // sending a message back to the socket
                    streamServer.SendMoreFrame(identity).SendFrame("a");

                    Assert.IsTrue(socketSignal.WaitOne(100));

                    socketSignal.Reset();

                    // sending a message back to the socket
                    streamServer.SendMoreFrame(identity).SendFrame("a");

                    // we remove the native socket so it should fail
                    Assert.IsFalse(socketSignal.WaitOne(100));

                    poller.Stop();
                }
            }
        }
예제 #50
0
        public void TestPollerDispose()
        {
            const int timerIntervalMillis = 10;

            var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis));

            var signal = new ManualResetEvent(false);

            var count = 0;

            timer.Elapsed += (s, a) =>
            {
                if (count++ == 5)
                    signal.Set();
            };

            NetMQPoller poller;
            using (poller = new NetMQPoller { timer })
            {
                poller.RunAsync();
                Assert.IsTrue(signal.WaitOne(500));
                Assert.IsTrue(poller.IsRunning);
                Assert.Throws<InvalidOperationException>(() => poller.Run());
            }

            Assert.IsFalse(poller.IsRunning);
            Assert.Throws<ObjectDisposedException>(() => poller.Run());
            Assert.Throws<ObjectDisposedException>(() => poller.Stop());
            Assert.Throws<ObjectDisposedException>(() => poller.Add(timer));
            Assert.Throws<ObjectDisposedException>(() => poller.Remove(timer));
        }
		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);
						}
					}
				}
			}
		}
예제 #52
0
        public void ContinueWith()
        {
            int threadId1 = 0;
            int threadId2 = 1;

            int runCount1 = 0;
            int runCount2 = 0;

            using (var poller = new NetMQPoller())
            {
                poller.RunAsync();

                var task = new Task(() =>
                {
                    threadId1 = Thread.CurrentThread.ManagedThreadId;
                    runCount1++;
                });

                var task2 = task.ContinueWith(t =>
                {
                    threadId2 = Thread.CurrentThread.ManagedThreadId;
                    runCount2++;
                }, poller);

                task.Start(poller);
                task.Wait();
                task2.Wait();

                Assert.AreEqual(threadId1, threadId2);
                Assert.AreEqual(1, runCount1);
                Assert.AreEqual(1, runCount2);
            }
        }
예제 #53
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();
            }
        }
예제 #54
0
        public void TwoThreads()
        {
            int count1 = 0;
            int count2 = 0;

            var allTasks = new ConcurrentBag<Task>();

            using (var poller = new NetMQPoller())
            {
                poller.RunAsync();

                Task t1 = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        var task = new Task(() => { count1++; });
                        allTasks.Add(task);
                        task.Start(poller);
                    }
                });

                Task t2 = Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < 100; i++)
                    {
                        var task = new Task(() => { count2++; });
                        allTasks.Add(task);
                        task.Start(poller);
                    }
                });

                t1.Wait(1000);
                t2.Wait(1000);
                Task.WaitAll(allTasks.ToArray(), 1000);

                Assert.AreEqual(100, count1);
                Assert.AreEqual(100, count2);
            }
        }
예제 #55
0
        public void Polling()
        {
            using (var speaker = new NetMQBeacon())
            using (var listener = new NetMQBeacon())
            {
                speaker.Configure(9999);

                speaker.Publish("Hello", s_publishInterval);

                var manualResetEvent = new ManualResetEvent(false);

                listener.Configure(9999);
                listener.Subscribe("H");

                string message = "";

                listener.ReceiveReady += (sender, args) =>
                {
                    message = listener.Receive().String;
                    manualResetEvent.Set();
                };

                using (var poller = new NetMQPoller { listener })
                {
                    poller.RunAsync();

                    manualResetEvent.WaitOne();

                    Assert.AreEqual("Hello", message);
                }
            }
        }
예제 #56
0
        public void ISynchronizeInvokeWorks()
        {
            using (var poller = new NetMQPoller())
            using (var signal = new ManualResetEvent(false))
            using (var timer = new System.Timers.Timer { AutoReset = false, Interval = 100, SynchronizingObject = poller, Enabled = true })
            {
                var isCorrectThread = false;

                poller.RunAsync();

                timer.Elapsed += (sender, args) =>
                {
                    isCorrectThread = poller.CanExecuteTaskInline;
                    Assert.True(signal.Set());
                };

                Assert.True(signal.WaitOne(TimeSpan.FromSeconds(2)));
                Assert.True(isCorrectThread);
            }
        }
예제 #57
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);
            }
        }
예제 #58
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);
            }
        }
예제 #59
0
        public void RunMultipleTimes()
        {
            int count = 0;

            const int timerIntervalMillis = 20;

            var timer = new NetMQTimer(TimeSpan.FromMilliseconds(timerIntervalMillis));
            timer.Elapsed += (s, a) =>
            {
                count++;

                if (count == 3)
                {
                    timer.Enable = false;
                }
            };

            using (var poller = new NetMQPoller { timer })
            {
                poller.RunAsync();

                Thread.Sleep(timerIntervalMillis * 6);

                poller.Stop();

                Assert.AreEqual(3, count);
            }
        }
예제 #60
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);
            }
        }