Example #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ForwarderDevice"/> class.
 /// </summary>
 /// <param name="context">The <see cref="NetMQContext"/> to use when creating the sockets.</param>
 /// <param name="poller">The <see cref="Poller"/> to use.</param>
 /// <param name="frontendBindAddress">The endpoint used to bind the frontend socket.</param>
 /// <param name="backendBindAddress">The endpoint used to bind the backend socket.</param>
 /// <param name="mode">The <see cref="DeviceMode"/> for the device.</param>		
 public ForwarderDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress,
     DeviceMode mode = DeviceMode.Threaded)
     : base(poller, context.CreateSubscriberSocket(), context.CreatePublisherSocket(), mode)
 {
     FrontendSetup.Bind(frontendBindAddress);
     BackendSetup.Bind(backendBindAddress);
 }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="QueueDevice"/> class.
        /// </summary>
        /// <param name="context">The <see cref="NetMQContext"/> to use when creating the sockets.</param>
        /// <param name="poller">The <see cref="Poller"/> to use.</param>
        /// <param name="frontendBindAddress">The endpoint used to bind the frontend socket.</param>
        /// <param name="backendBindAddress">The endpoint used to bind the backend socket.</param>
        /// <param name="mode">The <see cref="DeviceMode"/> for the device.</param>
        public QueueDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress,
			DeviceMode mode = DeviceMode.Threaded)
            : base(poller, context.CreateRouterSocket(), context.CreateDealerSocket(), mode)
        {
            FrontendSetup.Bind(frontendBindAddress);
            BackendSetup.Bind(backendBindAddress);
        }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamerDevice"/> class.
 /// </summary>
 /// <param name="context">The <see cref="NetMQContext"/> to use when creating the sockets.</param>
 /// <param name="poller">The <see cref="Poller"/> to use.</param>
 /// <param name="frontendBindAddress">The endpoint used to bind the frontend socket.</param>
 /// <param name="backendBindAddress">The endpoint used to bind the backend socket.</param>
 /// <param name="mode">The <see cref="DeviceMode"/> for the device.</param>		
 public StreamerDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress,
     DeviceMode mode = DeviceMode.Threaded)
     : base(poller, context.CreatePullSocket(), context.CreatePushSocket(), mode)
 {
     FrontendSetup.Bind(frontendBindAddress);
     BackendSetup.Bind(backendBindAddress);
 }
        public NetMQScaleoutMessageBus(IDependencyResolver resolver, NetMQScaleoutConfiguration configuration)
            : base(resolver, configuration)
        {
            _configuration = configuration;
            _context = NetMQContext.Create();

            var traceManager = resolver.Resolve<ITraceManager>();
            _trace = traceManager["SignalR." + typeof(NetMQScaleoutMessageBus).Name];

            SetupPublisher();

            ThreadPool.QueueUserWorkItem(Subscribe);
        }
Example #5
0
        protected WSSocket(NetMQContext context, IShimHandler<int> shimHandler )
        {
            int id = Interlocked.Increment(ref s_id);
            m_context = context;

            m_messagesPipe = context.CreatePairSocket();
            m_messagesPipe.Bind(string.Format("inproc://wsrouter-{0}", id));

            m_messagesPipe.ReceiveReady += OnMessagePipeReceiveReady;

            m_actor = new Actor<int>(context, shimHandler, id);

            m_messagesPipe.WaitForSignal();
        }
Example #6
0
        //!
        //! sender function, sending messages in sendMessageQueue to server (executed in separate thread)
        //!
        public void publisher()
        {
            //create NetMQ context
            NetMQContext ctx = NetMQContext.Create();

            NetMQ.Sockets.PublisherSocket sender = ctx.CreatePublisherSocket();
            sender.Connect("tcp://" + VPETSettings.Instance.serverIP + ":5557");

            while (isRunning)
            {
                if (sendMessageQueue.Count > 0)
                {
                    //  Debug.Log("Publisher: " + sendMessageQueue[0] as string);
                    sender.Send("client " + sendMessageQueue[0] as string);
                    sendMessageQueue.RemoveAt(0);
                }
            }

            sender.Disconnect("tcp://" + VPETSettings.Instance.serverIP + ":5557");
            sender.Close();
        }
Example #7
0
        static void Main(string[] args)
        {
            using (var ctx = NetMQContext.Create())
            {
                using (var client = ctx.CreateRequestSocket())
                {
                    client.Connect(CLIENT_ENDPOINT);
                    for (var i = 0; i < 10; i++)
                    {
                        var msg = new NetMQMessage();
                        msg.Append("Message_" + i);
                        client.SendMessage(msg);
                        Console.WriteLine("Sent Message {0}", msg.Last.ConvertToString());
                        var response = client.ReceiveMessage();
                        Console.WriteLine("Received Message {0}", response.Last.ConvertToString());
                    }

                    Console.ReadKey();
                }
            }
        }
Example #8
0
 public void Run()
 {
     Task.Run(() =>
     {
         using (NetMQContext ctx = NetMQContext.Create())
         {
             using (var client = ctx.CreateRequestSocket())
             {
                 client.Connect("tcp://127.0.0.1:5556");
                 while (true)
                 {
                     client.Send(string.Format("Hello from client {0}", clientName));
                     string fromServerMessage = client.ReceiveString();
                     Console.WriteLine("From Server: {0} running on ThreadId : {1}",
                                       fromServerMessage, Thread.CurrentThread.ManagedThreadId);
                     Thread.Sleep(5000);
                 }
             }
         }
     });
 }
Example #9
0
        public void SimplePubSub()
        {
            using (var context = NetMQContext.Create())
                using (var pub = context.CreatePublisherSocket())
                    using (var sub = context.CreateSubscriberSocket())
                    {
                        var port = pub.BindRandomPort("tcp://127.0.0.1");
                        sub.Connect("tcp://127.0.0.1:" + port);
                        sub.Subscribe("");

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

                        // Send the topic only
                        pub.SendFrame("A");

                        CollectionAssert.AreEqual(
                            new[] { "A" },
                            sub.ReceiveMultipartStrings());
                    }
        }
Example #10
0
        public void TwoTimers()
        {
            using (NetMQContext contex = NetMQContext.Create())
                using (Poller poller = new Poller())
                {
                    int count = 0;

                    NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(50));

                    NetMQTimer timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(24));


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

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

                    poller.AddTimer(timer);

                    int count2 = 0;

                    timer2.Elapsed += (s, a) => { count2++; };
                    poller.AddTimer(timer2);

                    Task.Factory.StartNew(poller.Start);

                    Thread.Sleep(300);

                    poller.Stop();

                    Assert.AreEqual(3, count);
                    Assert.AreEqual(6, count2);
                }
        }
Example #11
0
        public void RouterDealerMessaging()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (var server = context.CreateRouterSocket())
                {
                    server.Bind("tcp://127.0.0.1:5555");

                    using (var client = context.CreateDealerSocket())
                    {
                        client.Connect("tcp://127.0.0.1:5555");

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

                        client.SendMessage(clientOutgoingMessage);

                        NetMQMessage serverIncomingMessage = server.ReceiveMessage();

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

                        NetMQMessage serverOutgoingMessage = new NetMQMessage();

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

                        server.SendMessage(serverOutgoingMessage);

                        NetMQMessage incomingClientMessage = new NetMQMessage();
                        client.ReceiveMessage(incomingClientMessage);

                        Assert.AreEqual(1, incomingClientMessage.FrameCount);
                        Assert.AreEqual("World", incomingClientMessage[0].ConvertToString());
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        /// Start the processes and monitor them
        /// </summary>
        private void Master()
        {
            using (var context = NetMQContext.Create())
            {
            }
            //// Start processes
            var processPath = AppDomain.CurrentDomain.BaseDirectory;
            var workerPath  = Path.Combine(processPath, "MultiProcessing.Scratch.FirstWorker.exe");
            var firstWorker = StartProcess(workerPath);
            var loggerPath  = Path.Combine(processPath, "MultiProcessing.Scratch.Logger.exe");
            var logger      = StartProcess(loggerPath);
            var processes   = new Dictionary <Process, string>
            {
                { firstWorker, workerPath },
                { logger, loggerPath }
            };

            //// Wait for exit
            while (!this.exit)
            {
                var processList = processes.Keys.ToList();
                foreach (var process in processList)
                {
                    if (process.HasExited)
                    {
                        var newProcess = StartProcess(processes[process]);
                        processes[newProcess] = processes[process];
                        processes.Remove(process);
                    }
                }

                Thread.Sleep(1);
            }

            //// Kill the processes
            foreach (var processKey in processes.Keys)
            {
                processKey.Kill();
            }
        }
Example #13
0
        public void SetPgmSettings()
        {
            const int MegaBit  = 1024;
            const int MegaByte = 1024;

            using (NetMQContext context = NetMQContext.Create())
            {
                using (var pub = context.CreatePublisherSocket())
                {
                    pub.Options.MulticastHops             = 2;
                    pub.Options.MulticastRate             = 40 * MegaBit;       // 40 megabit
                    pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10);
                    pub.Options.SendBuffer = MegaByte * 10;                     // 10 megabyte

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

                    using (var sub = context.CreateSubscriberSocket())
                    {
                        sub.Options.ReceivevBuffer = MegaByte * 10;
                        sub.Bind("pgm://224.0.0.1:5555");

                        sub.Subscribe("");

                        pub.Send("Hi");

                        bool   more;
                        string message = sub.ReceiveString(out more);

                        Assert.IsFalse(more);
                        Assert.AreEqual("Hi", message);

                        Assert.AreEqual(2, pub.Options.MulticastHops);
                        Assert.AreEqual(40 * MegaBit, pub.Options.MulticastRate);
                        Assert.AreEqual(TimeSpan.FromMinutes(10), pub.Options.MulticastRecoveryInterval);
                        Assert.AreEqual(MegaByte * 10, pub.Options.SendBuffer);
                        Assert.AreEqual(MegaByte * 10, sub.Options.ReceivevBuffer);
                    }
                }
            }
        }
Example #14
0
        public void HasInTest()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket server = context.CreateRouterSocket())
                {
                    server.Bind("tcp://*:5557");

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

                    using (NetMQSocket client = context.CreateDealerSocket())
                    {
                        client.Connect("tcp://localhost:5557");

                        // 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.Send("1");

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

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

                        byte[] identity = server.Receive();
                        string message  = server.ReceiveString();

                        Assert.AreEqual(message, "1");

                        // we read the message, it should false again
                        Assert.IsFalse(server.HasIn);
                    }
                }
            }
        }
Example #15
0
        public void MultipleLargeMessages()
        {
            byte[] largeMessage = new byte[12000];

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

            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket pubSocket = context.CreatePublisherSocket())
                {
                    pubSocket.Bind("tcp://127.0.0.1:5558");

                    using (NetMQSocket subSocket = context.CreateSubscriberSocket())
                    {
                        subSocket.Connect("tcp://127.0.0.1:5558");
                        subSocket.Subscribe("");

                        Thread.Sleep(1000);

                        pubSocket.Send("");
                        subSocket.Receive();

                        for (int i = 0; i < 100; i++)
                        {
                            pubSocket.Send(largeMessage);

                            byte[] recvMesage = subSocket.Receive();

                            for (int j = 0; j < 12000; j++)
                            {
                                Assert.AreEqual(largeMessage[j], recvMesage[j]);
                            }
                        }
                    }
                }
            }
        }
Example #16
0
        public static void Main()
        {
            int count = 10000000;

            using (NetMQContext context = NetMQContext.Create())
            {
                NetMQQueue <int> queue = new NetMQQueue <int>(context);

                var task = Task.Factory.StartNew(() =>
                {
                    queue.Dequeue();

                    Stopwatch stopwatch = Stopwatch.StartNew();

                    for (int i = 0; i < count; i++)
                    {
                        queue.Dequeue();
                    }

                    stopwatch.Stop();

                    Console.WriteLine("Dequeueing items per second: {0:N0}", count / stopwatch.Elapsed.TotalSeconds);
                });

                queue.Enqueue(-1);

                Stopwatch writeStopwatch = Stopwatch.StartNew();

                for (int i = 0; i < count; i++)
                {
                    queue.Enqueue(i);
                }

                writeStopwatch.Stop();

                Console.WriteLine("Enqueueing items per second: {0:N0}", count / writeStopwatch.Elapsed.TotalSeconds);

                task.Wait();
            }
        }
Example #17
0
        public void Disconnect(string protocol)
        {
            using (var context = NetMQContext.Create())
            {
                using (var server1 = context.CreateDealerSocket())
                {
                    using (var server2 = context.CreateDealerSocket())
                    {
                        using (var client = context.CreateDealerSocket())
                        {
                            server1.Bind(protocol + "://localhost:55502");
                            server2.Bind(protocol + "://localhost:55503");

                            client.Connect(protocol + "://localhost:55502");
                            client.Connect(protocol + "://localhost:55503");

                            Thread.Sleep(100);

                            // we shoud be connected to both server
                            client.Send("1");
                            client.Send("2");

                            // make sure client is connected to both servers
                            server1.ReceiveString();
                            server2.ReceiveString();

                            // disconnect from server2, server 1 should receive all messages
                            client.Disconnect(protocol + "://localhost:55503");
                            Thread.Sleep(100);

                            client.Send("1");
                            client.Send("2");

                            server1.ReceiveString();
                            server1.ReceiveString();
                        }
                    }
                }
            }
        }
Example #18
0
        public void Monitoring()
        {
            using (var context = NetMQContext.Create())
                using (var rep = context.CreateResponseSocket())
                    using (var req = context.CreateRequestSocket())
                        using (var monitor = new NetMQMonitor(context, rep, "inproc://rep.inproc", SocketEvent.Accepted | SocketEvent.Listening))
                        {
                            bool listening = false;
                            bool accepted  = false;

                            monitor.Accepted  += (s, a) => { accepted = true; };
                            monitor.Listening += (s, a) => { listening = true; };

                            monitor.Timeout = TimeSpan.FromMilliseconds(100);

                            var pollerTask = Task.Factory.StartNew(monitor.Start);

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

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

                            rep.SkipFrame();

                            rep.Send("b");

                            req.SkipFrame();

                            Thread.Sleep(200);

                            Assert.IsTrue(listening);
                            Assert.IsTrue(accepted);

                            monitor.Stop();

                            Thread.Sleep(200);

                            Assert.IsTrue(pollerTask.IsCompleted);
                        }
        }
Example #19
0
        public void ASubscriberSocketThatGetDisconnectedBlocksItsContextFromBeingDisposed()
        {
            // NOTE two contexts here

            using (var subContext = NetMQContext.Create())
                using (var pubContext = NetMQContext.Create())
                    using (var pub = pubContext.CreatePublisherSocket())
                        using (var sub = subContext.CreateSubscriberSocket())
                        {
                            pub.Options.Linger      = TimeSpan.FromSeconds(0);
                            pub.Options.SendTimeout = TimeSpan.FromSeconds(2);

                            sub.Options.Linger = TimeSpan.FromSeconds(0);

                            sub.Connect("tcp://localhost:12345");
                            sub.Subscribe("");

//                Thread.Sleep(1000);

                            pub.Bind("tcp://localhost:12345");

                            // NOTE the test fails if you remove this sleep
                            Thread.Sleep(1000);

                            for (var i = 0; i < 100; i++)
                            {
                                var sent = "msg-" + i;

                                pub.Send(sent);

                                string received;
                                Assert.IsTrue(sub.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out received));
                                Assert.AreEqual(sent, received);
                            }

                            pub.Close();

//                Thread.Sleep(1000);
                        }
        }
Example #20
0
        public void ControlSocketObservedMessages()
        {
            using (var context = NetMQContext.Create())
            using (var front = context.CreateRouterSocket())
            using (var back = context.CreateDealerSocket())
            using (var controlPush = context.CreatePushSocket())
            using (var controlPull = context.CreatePullSocket())
            {
                front.Bind("inproc://frontend");
                back.Bind("inproc://backend");

                controlPush.Bind("inproc://control");
                controlPull.Connect("inproc://control");

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

                using (var client = context.CreateRequestSocket())
                using (var server = context.CreateResponseSocket())
                {
                    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(controlPull.ReceiveFrameBytes());     // receive identity
                Assert.IsEmpty(controlPull.ReceiveFrameString()); // pull terminator
                Assert.AreEqual("hello", controlPull.ReceiveFrameString());

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

                proxy.Stop();
            }
        }
Example #21
0
        public void TwoTimers()
        {
            using (NetMQContext contex = NetMQContext.Create())
                using (Poller poller = new Poller())
                {
                    int count = 0;

                    NetMQTimer timer = new NetMQTimer(TimeSpan.FromMilliseconds(52));

                    NetMQTimer timer2 = new NetMQTimer(TimeSpan.FromMilliseconds(24));


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

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

                    poller.AddTimer(timer);

                    int count2 = 0;

                    timer2.Elapsed += (s, a) => { count2++; };
                    poller.AddTimer(timer2);

                    poller.PollTillCancelledNonBlocking();

                    Thread.Sleep(300);

                    poller.CancelAndJoin();

                    Assert.AreEqual(3, count);
                    Assert.AreEqual(6, count2);
                }
        }
Example #22
0
        public void SendingTwoRequestsInaRow()
        {
            using (NetMQContext ctx = NetMQContext.Create())
            {
                using (var rep = ctx.CreateResponseSocket())
                {
                    rep.Bind("tcp://localhost:5002");

                    using (var req = ctx.CreateRequestSocket())
                    {
                        req.Connect("tcp://localhost:5002");

                        req.Send("Hi");

                        bool more;
                        rep.Receive(out more);

                        var ex = Assert.Throws <FiniteStateMachineException>(() => req.Send("Hi2"));
                    }
                }
            }
        }
Example #23
0
        private static void Main()
        {
            using (var context = NetMQContext.Create())
                using (var response = context.CreateResponseSocket())
                {
                    string address = GetComputerLanIP();

                    if (!string.IsNullOrEmpty(address))
                    {
                        Console.WriteLine("Binding tcp://{0}:{1}", address, PortNumber);
                        response.Bind(string.Format("tcp://{0}:{1}", address, PortNumber));

                        while (true)
                        {
                            bool   hasMore;
                            string msg = response.ReceiveFrameString(out hasMore);
                            if (string.IsNullOrEmpty(msg))
                            {
                                Console.WriteLine("No msg received.");
                                break;
                            }

                            Console.WriteLine("Msg received! {0}", msg);
                            response.Send(msg, false, hasMore);

                            Thread.Sleep(1000);
                        }

                        response.Options.Linger = TimeSpan.Zero;
                    }
                    else
                    {
                        Console.WriteLine("Wrong IP address");
                    }

                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                }
        }
Example #24
0
        void Start()
        {
            PseudoRandom rand = PseudoRandom.getInstance();

            ThreadPool.QueueUserWorkItem((obj) => {
                using (var context = NetMQContext.Create())
                    using (pubSocket = context.CreatePublisherSocket()) {
                        ConsoleEx.DebugLog("Publisher socket binding...", ConsoleEx.RED);

                        pubSocket.Options.SendHighWatermark = 1000;
                        pubSocket.Bind("tcp://*:52323");

                        for (var i = 0; i < 50; i++)
                        {
                            if (quite)
                            {
                                break;
                            }

                            var randomizedTopic = rand.next(1000);
                            if (randomizedTopic > 50)
                            {
                                var msg = "TopicA msg-" + i;
                                ConsoleEx.DebugLog("Sending message : " + msg, ConsoleEx.RED);
                                pubSocket.SendMore("TopicA").Send(msg);
                            }
                            else
                            {
                                var msg = "TopicB msg-" + i;
                                ConsoleEx.DebugLog("Sending message : " + msg, ConsoleEx.RED);
                                pubSocket.SendMore("TopicB").Send(msg);
                            }

                            Thread.Sleep(500);
                        }
                        ConsoleEx.DebugLog("Publisher job is down.", ConsoleEx.RED);
                    }
            });
        }
Example #25
0
 static void Main(string[] args)
 {
     using (var context = NetMQContext.Create())                      //create netmqcontext
         using (var sender = context.CreateDealerSocket())            // using dealersocket
         {
             sender.Connect("tcp://127.0.0.1:9045");                  //connect router socket
             System.Timers.Timer aTimer = new System.Timers.Timer();  //timer initalization
             aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); //event creation for timer
             aTimer.Interval = 60000;                                 //set the timer interval
             aTimer.Enabled  = true;                                  //set the enabled timer
             aTimer.Start();                                          //start the timer
             while (true)                                             //infinitive loop starts
             {
                 if (!Console.KeyAvailable)
                 {
                     var    message = new NetMQMessage();               //create netmqmessage
                     String guid    = Guid.NewGuid().ToString();        //create the guid generation
                     message.Append("GoodApp" + '_' + guid.ToString()); //add the guid in netmqmessage
                     if (flag == true)
                     {
                         sender.SendMessage(message);                        //sending the message to router
                         Console.WriteLine(message.First.ConvertToString()); //print the guid
                     }
                     Thread.Sleep(500);
                 }
                 else
                 {
                     if (flag == true) //any key press is available close the application
                     {
                         var process = Process.GetCurrentProcess();
                         if (process.ProcessName == "GoodApplication.vshost" || process.ProcessName == "GoodApplication.exe" || process.ProcessName == "GoodApplication")
                         {
                             process.Kill();
                         }
                     }
                 }
             }
         }
 }
        public void ReceiveBeforeSending()
        {
            using (NetMQContext ctx = NetMQContext.Create())
            {
                using (var rep = ctx.CreateResponseSocket())
                {
                    rep.Bind("tcp://localhost:5001");


                    using (var req = ctx.CreateRequestSocket())
                    {
                        req.Connect("tcp://localhost:5001");

                        bool more;

                        var ex = Assert.Throws <NetMQException>(() => req.ReceiveString(out more));

                        Assert.AreEqual(ErrorCode.EFSM, ex.ErrorCode);
                    }
                }
            }
        }
Example #27
0
        public void StoppingProxyDisengagesFunctionality()
        {
            using (var context = NetMQContext.Create())
            using (var front = context.CreateRouterSocket())
            using (var back = context.CreateDealerSocket())
            {
                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 = context.CreateRequestSocket())
                using (var server = context.CreateResponseSocket())
                {
                    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 Poller(front, back))
                    {
                        poller.PollTillCancelledNonBlocking();

                        client.SendFrame("anyone there?");

                        // Should no longer receive any messages
                        Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50)));

                        poller.CancelAndJoin();
                    }
                }
            }
        }
Example #28
0
        private static void StartServerNetMq(NetMQContext context)
        {
            using (NetMQSocket serverSocket = context.CreateResponseSocket())
            {
                serverSocket.Options.SendTimeout = TimeSpan.FromMilliseconds(60000);

                serverSocket.Bind(string.Format("tcp://*:{0}", 2804));
                string message = string.Empty;
                string retMsg  = string.Empty;

                Console.WriteLine("Server started;");

                while (true)
                {
                    //log.WriteLog("Received command {0}, {1} bytes returned.", message, results.Length);
                    try
                    {
                        message = serverSocket.ReceiveString();
                        //Console.WriteLine("Message: {0} received.", message);
                        if (message == "Who's there?")
                        {
                            TimeSpan timeSinceLast = DateTime.Now - lastVerification;

                            //if (verificationState == VerificationState.Verifying && timeSinceLast.TotalSeconds > 15)
                            //    name = string.Empty;

                            retMsg = name;
                        }

                        serverSocket.Send(retMsg);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error sending data; message: {0}, error: {1}", message, e);
                        serverSocket.Send(string.Empty);
                    }
                }
            }
        }
Example #29
0
        public void SimplePublishSubscribe()
        {
            using (var context = NetMQContext.Create())
                using (var speaker = new NetMQBeacon(context))
                    using (var listener = new NetMQBeacon(context))
                    {
                        speaker.Configure(9999);
                        Console.WriteLine(speaker.Hostname);

                        speaker.Publish("Hello", s_publishInterval);

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

                        string peerName;
                        string message = listener.ReceiveString(out peerName);

                        Console.WriteLine(peerName);

                        Assert.AreEqual("Hello", message);
                    }
        }
Example #30
0
        private void ConsumerThread()
        {
            using (var context = NetMQContext.Create())
                using (var socket = CreateConsumerSocket(context))
                {
                    socket.Bind("tcp://*:9091");

                    foreach (var messageSize in s_messageSizes)
                    {
                        var watch = Stopwatch.StartNew();

                        Consume(socket, messageSize);

                        long   ticks          = watch.ElapsedTicks;
                        double seconds        = (double)ticks / Stopwatch.Frequency;
                        double msgsPerSec     = MsgCount / seconds;
                        double megabitsPerSec = msgsPerSec * messageSize * 8 / 1000000;

                        Console.Out.WriteLine(" {0,-6} {1,10:0.0} {2,8:0.00}", messageSize, msgsPerSec, megabitsPerSec);
                    }
                }
        }
Example #31
0
        public void TopicPubSub()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var pub = contex.CreateXPublisherSocket())
                {
                    pub.Bind("tcp://127.0.0.1:5002");

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

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

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

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

                        bool more;

                        string m = sub.ReceiveString(out more);

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

                        string m2 = sub.ReceiveString(out more);

                        Assert.AreEqual("Hello", m2);
                        Assert.False(more);
                    }
                }
            }
        }
Example #32
0
        public void TestKeepAlive()
        {
            // there is no way to test tcp keep alive without disconnect the cable, we just testing that is not crashing the system
            using (var context = NetMQContext.Create())
                using (var rep = context.CreateResponseSocket())
                    using (var req = context.CreateRequestSocket())
                    {
                        rep.Options.TcpKeepalive         = true;
                        rep.Options.TcpKeepaliveIdle     = TimeSpan.FromSeconds(5);
                        rep.Options.TcpKeepaliveInterval = TimeSpan.FromSeconds(1);

                        req.Options.TcpKeepalive         = true;
                        req.Options.TcpKeepaliveIdle     = TimeSpan.FromSeconds(5);
                        req.Options.TcpKeepaliveInterval = TimeSpan.FromSeconds(1);

                        var port = rep.BindRandomPort("tcp://127.0.0.1");
                        req.Connect("tcp://127.0.0.1:" + port);

                        bool more;

                        req.SendFrame("1");

                        Assert.AreEqual("1", rep.ReceiveFrameString(out more));
                        Assert.IsFalse(more);

                        rep.SendFrame("2");

                        Assert.AreEqual("2", req.ReceiveFrameString(out more));
                        Assert.IsFalse(more);

                        Assert.IsTrue(req.Options.TcpKeepalive);
                        Assert.AreEqual(TimeSpan.FromSeconds(5), req.Options.TcpKeepaliveIdle);
                        Assert.AreEqual(TimeSpan.FromSeconds(1), req.Options.TcpKeepaliveInterval);

                        Assert.IsTrue(rep.Options.TcpKeepalive);
                        Assert.AreEqual(TimeSpan.FromSeconds(5), rep.Options.TcpKeepaliveIdle);
                        Assert.AreEqual(TimeSpan.FromSeconds(1), rep.Options.TcpKeepaliveInterval);
                    }
        }
Example #33
0
        static void Subscriber(NetMQContext context)
        {
            using (var serverSocket = context.CreateSubscriberSocket())
            {
                serverSocket.Subscribe(new byte[0]); //.Subscribe("tcp://*:5555");
                for (int i = 0; i <= 8; i++)
                {
                    serverSocket.Connect(string.Format("tcp://127.0.0.1:{0}", 5555 + i));//"tcp://*:5555");
                }
                while (true)
                {
                    string message = serverSocket.ReceiveString();

                    Console.WriteLine("Receive message {0}", message);

                    if (message == "exit")
                    {
                        break;
                    }
                }
            }
        }
Example #34
0
        /// <summary>
        /// Create a new instance of a Proxy (NetMQ.Proxy)
        /// with the given sockets to serve as a front-end, a back-end, and a control socket.
        /// </summary>
        /// <param name="publisherAddress">the address that messages will be forwarded from</param>
        /// <param name="subscriberAddress">the address that messages should be sent to</param>
        /// <param name="heartbeat">the timespan at which to send HEARTBEAT messages (in milliseconds) - you can set this to zero if not needed</param>
        /// <param name="control">this socket will have messages also sent to it - you can set this to null if not needed</param>
        public ZeroMqHub(string publisherAddress, string subscriberAddress, int heartbeat = 0, NetMQSocket control = null)
        {
            _subscriberAddress = subscriberAddress;
            _publisherAddress  = publisherAddress;
            var context = NetMQContext.Create();

            _subscriber = context.CreateXSubscriberSocket();
            _publisher  = context.CreateXPublisherSocket();
            _control    = control;

            if (heartbeat > 0)
            {
                _heartbeat          = new NetMQTimer(heartbeat);
                _heartbeat.Elapsed += (s, a) => _publisher.Send("HEARTBEAT");
            }

            Name          = "XPub-XSub";
            PSJobTypeName = typeof(ZeroMqHub).Name;

            _subscriber.Bind(subscriberAddress);
            _publisher.Bind(publisherAddress);
        }
Example #35
0
        static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("usage: local_lat <bind-to> <message-size> <roundtrip-count>");
                return(1);
            }

            string bindTo         = args[0];
            int    messageSize    = int.Parse(args[1]);
            int    roundtripCount = int.Parse(args[2]);

            var context   = NetMQContext.Create();
            var repSocket = context.CreateResponseSocket();

            repSocket.Bind(bindTo);

            Msg message = new Msg();

            message.InitEmpty();

            for (int i = 0; i != roundtripCount; i++)
            {
                repSocket.Receive(ref message, SendReceiveOptions.None);
                if (message.Size != messageSize)
                {
                    Console.WriteLine("message of incorrect size received. Received: " + message.Size + " Expected: " + messageSize);
                    return(-1);
                }

                repSocket.Send(ref message, SendReceiveOptions.None);
            }

            message.Close();
            repSocket.Close();
            context.Terminate();

            return(0);
        }
Example #36
0
 public PublisherShimHandler(NetMQContext context)
     : base(context)
 {
     m_identities = new List<byte[]>();
     m_subscriptions = new Mtrie();
 }
 protected override PullSocket CreateConsumerSocket(NetMQContext context)
 {
     return context.CreatePullSocket();
 }
Example #38
0
 protected override NetMQSocket CreateClientSocket(NetMQContext context)
 {
     return context.CreateRequestSocket();
 }
Example #39
0
 protected override NetMQSocket CreateServerSocket(NetMQContext context)
 {
     return context.CreateResponseSocket();
 }
        protected override void Dispose(bool disposing)
        {
            if(disposing)
            {
                if(_publisherSocket != null)
                {
                    _publisherSocket.Dispose();
                    _publisherSocket = null;
                }

                foreach(NetMQSocket subscriber in _subscriberSockets.ToArray())
                {
                    subscriber.Dispose();
                    _subscriberSockets.Remove(subscriber);
                }

                // Setting running to false will stop the subscriber tasks
                _running = false;

                if(_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
            base.Dispose(disposing);
        }
 protected override PushSocket CreateProducerSocket(NetMQContext context)
 {
     return context.CreatePushSocket();
 }
Example #42
0
 public WSPublisher(NetMQContext context) : base(context, new PublisherShimHandler(context))
 {
 }
Example #43
0
 public RouterShimHandler(NetMQContext context)
     : base(context)
 {
 }
Example #44
0
 public WSRouter(NetMQContext context)
     : base(context, new RouterShimHandler(context))
 {
 }