コード例 #1
0
ファイル: SocketTests.cs プロジェクト: lovmoen/netmq
        public void HasOutTest()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket server = context.CreateDealerSocket())
                {
                    server.Bind("tcp://*:5557");

                    // no client is connected so we don't have out
                    Assert.IsFalse(server.HasOut);

                    using (NetMQSocket client = context.CreateDealerSocket())
                    {
                        Assert.IsFalse(client.HasOut);

                        client.Connect("tcp://localhost:5557");

                        Thread.Sleep(100);

                        // client is connected so server should have out now, client as well
                        Assert.IsTrue(server.HasOut);
                        Assert.IsTrue(client.HasOut);
                    }

                    Thread.Sleep(100);

                    // client is disposed,server shouldn't have out now
                    Assert.IsFalse(server.HasOut);
                }
            }
        }
コード例 #2
0
ファイル: SocketTests.cs プロジェクト: lovmoen/netmq
        public void BindToLocal()
        {
            var validAliasesForLocalHost = new[] { "127.0.0.1", "localhost", System.Net.Dns.GetHostName() };

            foreach (var alias in validAliasesForLocalHost)
            {
                using (NetMQContext context = NetMQContext.Create())
                {
                    using (NetMQSocket localDealer = context.CreateDealerSocket())
                    {
                        localDealer.Bind("tcp://*:5002");

                        using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                        {
                            connectingDealer.Connect("tcp://" + alias + ":5002");

                            localDealer.Send("test");

                            Assert.AreEqual("test", connectingDealer.ReceiveString());
                            Console.WriteLine(alias + " connected ");
                        }
                    }
                }
            }
        }
コード例 #3
0
        public void AddSocketDuringWork()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                // we are using three responses to make sure we actually move the correct socket and other sockets still work
                using (var router = contex.CreateRouterSocket())
                    using (var router2 = contex.CreateRouterSocket())
                    {
                        router.Bind("tcp://127.0.0.1:5002");
                        router2.Bind("tcp://127.0.0.1:5003");

                        using (var dealer = contex.CreateDealerSocket())
                            using (var dealer2 = contex.CreateDealerSocket())
                                using (Poller poller = new Poller())
                                {
                                    dealer.Connect("tcp://127.0.0.1:5002");
                                    dealer2.Connect("tcp://127.0.0.1:5003");

                                    bool router1arrived = false;
                                    bool router2arrived = false;


                                    bool more;

                                    router2.ReceiveReady += (s, a) =>
                                    {
                                        router2.Receive(out more);
                                        router2.Receive(out more);
                                        router2arrived = true;
                                    };

                                    router.ReceiveReady += (s, a) =>
                                    {
                                        router1arrived = true;

                                        router.Receive(out more);
                                        router.Receive(out more);

                                        poller.AddSocket(router2);
                                    };

                                    poller.AddSocket(router);

                                    Task task = Task.Factory.StartNew(poller.Start);

                                    dealer.Send("1");
                                    Thread.Sleep(300);
                                    dealer2.Send("2");
                                    Thread.Sleep(300);

                                    poller.Stop(true);
                                    task.Wait();

                                    Assert.IsTrue(router1arrived);
                                    Assert.IsTrue(router2arrived);
                                }
                    }
            }
        }
コード例 #4
0
        private void ProxyThread()
        {
            RouterSocket router = null;
            DealerSocket dealer = null;

            try
            {
                router = _ctx.CreateRouterSocket();
                dealer = _ctx.CreateDealerSocket();
                router.Bind(_frontendAddress);
                switch (_backendCxMode)
                {
                case ConnectionMode.Connect:
                    dealer.Connect(_backendAddress);
                    break;

                case ConnectionMode.Bind:
                    dealer.Bind(_backendAddress);
                    break;
                }

                router.Options.Linger = TimeSpan.Zero;
                dealer.Options.Linger = TimeSpan.Zero;
                var xproxy = new Proxy(router, dealer, null);
                xproxy.Start();
            }
            catch (TerminatingException)
            {
            }
            finally
            {
                if (router != null)
                {
                    try
                    {
                        router.Dispose();
                    }
                    catch (NetMQException)
                    {
                    }
                }
                if (dealer != null)
                {
                    try
                    {
                        dealer.Dispose();
                    }
                    catch (NetMQException)
                    {
                    }
                }
            }
        }
コード例 #5
0
ファイル: MDPWorker.cs プロジェクト: wangkai2014/netmq
        /// <summary>
        /// Connect or re-connect to the broker.
        /// </summary>
        private void Connect()
        {
            // if the socket exists dispose it and re-create one
            if (!ReferenceEquals(m_worker, null))
            {
                m_worker.Unbind(m_brokerAddress);
                m_worker.Dispose();
            }

            m_worker = m_ctx.CreateDealerSocket();
            // set identity if provided
            if (m_identity != null && m_identity.Length > 0)
            {
                m_worker.Options.Identity = m_identity;
            }

            // hook up the received message processing method before the socket is connected
            m_worker.ReceiveReady += ProcessReceiveReady;

            m_worker.Connect(m_brokerAddress);

            Log(string.Format("[WORKER] connected to broker at {0}", m_brokerAddress));

            // signal that worker is connected
            m_connected = true;
            // send READY to broker since worker is connected
            Send(MDPCommand.Ready, m_serviceName, null);
            // reset liveliness to active broker
            m_liveliness = _heartbeat_liveliness;
            // set point in time for next heatbeat
            m_heartbeatAt = DateTime.UtcNow + HeartbeatDelay;
        }
コード例 #6
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);
 }
コード例 #7
0
ファイル: QueueDevice.cs プロジェクト: bubbafat/netmq
        /// <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);
        }
コード例 #8
0
        private static void WorkerTaskB(object portNumber)
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (DealerSocket worker = context.CreateDealerSocket())
                {
                    worker.Options.Identity = Encoding.Unicode.GetBytes("B");
                    worker.Connect(string.Format("tcp://localhost:{0}", portNumber));

                    int total = 0;

                    bool end = false;

                    while (!end)
                    {
                        string request = worker.ReceiveString();

                        if (request.Equals("END"))
                        {
                            end = true;
                        }
                        else
                        {
                            total++;
                        }
                    }

                    Console.WriteLine("B Received: {0}", total);
                }
            }
        }
コード例 #9
0
        void CreateClient()
        {
            switch (_type)
            {
            case MQClientType.Request:
                _clientSocket = _context.CreateRequestSocket();
                break;

            case MQClientType.Subscriber:
                _clientSocket = _context.CreateSubscriberSocket();
                break;

            case MQClientType.Dealer:
                _clientSocket = _context.CreateDealerSocket();
                break;

            case MQClientType.Stream:
                _clientSocket = _context.CreateStreamSocket();
                break;

            case MQClientType.Pull:
                _clientSocket = _context.CreatePullSocket();
                break;

            case MQClientType.XSubscriber:
                _clientSocket = _context.CreateXSubscriberSocket();
                break;

            default:
                _clientSocket = _context.CreateRequestSocket();
                break;
            }
            _clientSocket.Connect("tcp://" + _ip + ":" + _port);
        }
コード例 #10
0
ファイル: ExampleTests.cs プロジェクト: xingfeT/zproto
        public void BinaryTest()
        {
            Action <Example> setMessage = m =>
            {
                m.Id = Example.MessageId.Binary;

                m.Binary.Sequence = 123;
                FillArray(m.Binary.Flags, 123);
                m.Binary.PublicKey  = Encoding.ASCII.GetBytes("Captcha Diem");
                m.Binary.Identifier = Guid.Parse("DED9D22A-FCE1-488B-8761-84752ACC113E");
            };

            Action <Example> checkMessage = m =>
            {
                Assert.That(m.Id, Is.EqualTo(Example.MessageId.Binary));
                Assert.That(m.Binary.Sequence, Is.EqualTo(123));
                Assert.That(m.Binary.Flags[0], Is.EqualTo(123));
                Assert.That(m.Binary.Flags[m.Binary.Flags.Length - 1], Is.EqualTo(123));
                Assert.That(m.Binary.PublicKey, Is.EqualTo(Encoding.ASCII.GetBytes("Captcha Diem")));
                Assert.That(m.Binary.Identifier, Is.EqualTo(Guid.Parse("DED9D22A-FCE1-488B-8761-84752ACC113E")));
            };

            using (NetMQContext context = NetMQContext.Create())
                using (var client = context.CreateDealerSocket())
                    using (var server = context.CreateRouterSocket())
                    {
                        server.Bind("inproc://zprototest");
                        client.Connect("inproc://zprototest");

                        Example clientMessage = new Example();
                        Example serverMessage = new Example();

                        for (int i = 0; i < 2; i++)
                        {
                            // client send message to server
                            setMessage(clientMessage);
                            clientMessage.Send(client);

                            // server receive the message
                            serverMessage.Receive(server);

                            // check that message received ok
                            Assert.That(serverMessage.RoutingId, Is.Not.Null);
                            checkMessage(serverMessage);

                            // reply to client, no need to set the message, using client data
                            serverMessage.Send(server);

                            // client receive the message
                            clientMessage.Receive(client);

                            // check that message received ok
                            Assert.That(clientMessage.RoutingId, Is.Null);
                            checkMessage(clientMessage);
                        }
                    }
        }
コード例 #11
0
 public void Start()
 {
     poller       = new Poller();
     clientSocket = context.CreateDealerSocket();
     clientSocket.ReceiveReady += clientSocket_ReceiveReady;
     clientSocket.Connect(address);
     scheduler = new NetMQScheduler(context, poller);
     Task.Factory.StartNew(poller.Start, TaskCreationOptions.LongRunning);
 }
コード例 #12
0
        public void CancelTimer()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                // we are using three responses to make sure we actually move the correct socket and other sockets still work
                using (var router = contex.CreateRouterSocket())
                {
                    router.Bind("tcp://127.0.0.1:5002");

                    using (var dealer = contex.CreateDealerSocket())
                        using (Poller poller = new Poller())
                        {
                            dealer.Connect("tcp://127.0.0.1:5002");


                            bool timerTriggered = false;

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

                            // the timer will jump after 100ms
                            poller.AddTimer(timer);

                            bool messageArrived = false;

                            router.ReceiveReady += (s, a) =>
                            {
                                bool isMore;
                                router.Receive(out isMore);
                                router.Receive(out isMore);

                                messageArrived = true;
                                poller.RemoveTimer(timer);
                            };

                            poller.AddSocket(router);

                            Task.Factory.StartNew(poller.Start);

                            Thread.Sleep(20);

                            dealer.Send("hello");

                            Thread.Sleep(300);

                            poller.Stop();

                            Assert.IsTrue(messageArrived);
                            Assert.IsFalse(timerTriggered);
                        }
                }
            }
        }
コード例 #13
0
ファイル: SocketTests.cs プロジェクト: lovmoen/netmq
        public void Ipv6ToIpv4()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket localDealer = context.CreateDealerSocket())
                {
                    localDealer.Options.IPv4Only = false;
                    localDealer.Bind(string.Format("tcp://*:5002"));
                    using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                    {
                        connectingDealer.Connect("tcp://" + IPAddress.Loopback.ToString() + ":5002");

                        connectingDealer.Send("test");

                        Assert.AreEqual("test", localDealer.ReceiveString());
                    }
                }
            }
        }
コード例 #14
0
 public void DisposeImmediatly()
 {
     using (NetMQContext context = NetMQContext.Create())
     {
         using (NetMQSocket server = context.CreateDealerSocket())
         {
             server.Bind("tcp://*:5557");
         }
     }
 }
コード例 #15
0
ファイル: SocketTests.cs プロジェクト: lovmoen/netmq
        public void BindRandom()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket randomDealer = context.CreateDealerSocket())
                {
                    int port = randomDealer.BindRandomPort("tcp://*");

                    using (NetMQSocket connectingDealer = context.CreateDealerSocket())
                    {
                        connectingDealer.Connect("tcp://127.0.0.1:" + port);

                        randomDealer.Send("test");

                        Assert.AreEqual("test", connectingDealer.ReceiveString());
                    }
                }
            }
        }
コード例 #16
0
ファイル: Client.cs プロジェクト: BryantN/Sorry
        /// <summary>
        /// Initializes a new instance of the Client class
        /// </summary>
        /// <param name="connectionString">How the server should be set up, to listen on TCP port 7954 to all incoming connections: "tcp://172.154.231.18:7954"</param>
        public Client(string connectionString)
        {
            Id = Guid.NewGuid(); // Generate an ID for this client

            NetMQContext context = NetMQContext.Create();

            clientConnectionString        = connectionString;
            clientSocket                  = context.CreateDealerSocket();
            clientSocket.Options.Identity = Id.ToByteArray();
            clientSocket.Connect(clientConnectionString);
        }
コード例 #17
0
        static void Main(string[] args)
        {
            int count = 1000000;

            //BufferPool.SetBufferManagerBufferPool(1024 * 1024 * 10, 1024);

            using (NetMQContext context = NetMQContext.Create())
            {
                using (var router = context.CreateRouterSocket())
                {
                    router.Options.SendHighWatermark = 0;
                    router.Bind("tcp://*:5555");

                    List <DealerSocket> dealers    = new List <DealerSocket>();
                    List <byte[]>       identities = new List <byte[]>();

                    Random random = new Random();

                    for (int i = 0; i < 100; i++)
                    {
                        var dealer = context.CreateDealerSocket();

                        byte[] identity = new byte[50];
                        random.NextBytes(identity);

                        dealer.Options.Identity             = identity;
                        dealer.Options.ReceiveHighWatermark = 0;
                        dealer.Connect("tcp://localhost:5555");

                        dealers.Add(dealer);
                        identities.Add(identity);
                    }

                    Thread.Sleep(1000);

                    Stopwatch stopwatch = Stopwatch.StartNew();

                    for (int i = 0; i < count; i++)
                    {
                        router.SendMore(identities[i % identities.Count]).Send("E");
                    }

                    stopwatch.Stop();

                    Console.WriteLine("{0:N1} in second", count / stopwatch.Elapsed.TotalSeconds);
                    Console.ReadLine();

                    foreach (var dealerSocket in dealers)
                    {
                        dealerSocket.Dispose();
                    }
                }
            }
        }
コード例 #18
0
        public ParanoidPirateWorker()
        {
            _interval = INTERVAL_INIT;
            _liveness = Paranoid.HEARTBEAT_LIVENESS;

            _context = NetMQContext.Create();
            _worker  = _context.CreateDealerSocket();
            _worker.Options.Identity = Encoding.Unicode.GetBytes(Guid.NewGuid().ToString());

            var shortId = Guid.Parse(Encoding.Unicode.GetString(_worker.Options.Identity)).ToPrintable();

            Console.WriteLine("Worker: {0}", shortId);
        }
コード例 #19
0
ファイル: NetMqPusher.cs プロジェクト: adamtha/ServiceBlocks
        protected override void ConsumerAction()
        {
            using (NetMQContext ctx = NetMQContext.Create())
            {
                using (DealerSocket socket = ctx.CreateDealerSocket())
                {
                    socket.Connect(Address); //TODO: implement automatic reconnects

                    foreach (NetMQMessage message in Queue.GetConsumingEnumerable())
                    {
                        socket.SendMessage(message);
                    }
                }
            }
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: fhchina/netmq
        /// <summary>
        ///     create the DEALER socket and connect it to QUEUE backend
        ///     set the identity
        /// send the initial READY message
        /// </summary>
        private static DealerSocket GetWorkerSocket(NetMQContext ctx, bool verbose, int id)
        {
            var worker = ctx.CreateDealerSocket();

            worker.Options.Identity = Encoding.UTF8.GetBytes("Worker_" + id);

            worker.Connect(Commons.QUEUE_BACKEND);

            if (verbose)
            {
                Console.WriteLine("[WORKER] {0} sending 'READY'.", Encoding.UTF8.GetString(worker.Options.Identity));
            }

            // send READY
            worker.Send(Commons.PPP_READY);

            return(worker);
        }
コード例 #21
0
ファイル: SocketTests.cs プロジェクト: lovmoen/netmq
        public void CheckSendAgainException()
        {
            using (NetMQContext context = NetMQContext.Create())
            {
                using (var routerSocket = context.CreateRouterSocket())
                {
                    routerSocket.Bind("tcp://127.0.0.1:5555");
                    routerSocket.Options.Linger = TimeSpan.Zero;

                    using (var dealerSocket = context.CreateDealerSocket())
                    {
                        dealerSocket.Options.SendHighWatermark = 1;
                        dealerSocket.Options.Linger            = TimeSpan.Zero;
                        dealerSocket.Connect("tcp://127.0.0.1:5555");

                        dealerSocket.Send("1", true, false);
                        dealerSocket.Send("2", true, false);
                    }
                }
            }
        }
コード例 #22
0
        public void Start()
        {
            _context = NetMQContext.Create();
            // Dealer can send any number of requests and just wait for the answers
            _socket = _context.CreateDealerSocket();
            // REP can send only one request and wait reply for that before sending more
            //_socket = _context.CreateRequestSocket();
            var clientId = Guid.NewGuid();

            _socket.Options.Identity = Encoding.Unicode.GetBytes(clientId.ToString());
            Console.WriteLine("Client: {0}", clientId.ToPrintable());

            _socket.Connect(_endPoint);

            _socket.ReceiveReady += _socket_ReceiveReady;

            _poller = new Poller();
            _poller.AddSocket(_socket);

            Task.Factory.StartNew(() => Run(), TaskCreationOptions.LongRunning);
        }
コード例 #23
0
ファイル: SocketTests.cs プロジェクト: lovmoen/netmq
        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);
                    }
                }
            }
        }
コード例 #24
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());
                    }
                }
            }
        }
コード例 #25
0
        public TResponse SendRequest(TRequest request)
        {
            using (var socket = _context.CreateDealerSocket())
            {
                var clientId = Guid.NewGuid();
                socket.Options.Identity = Encoding.Unicode.GetBytes(clientId.ToString());

                socket.Connect(_bindEndPoint);

                var envelope = new NetMQFrame(Encoding.UTF8.GetBytes(request.ToString()));
                var body     = new NetMQFrame(request.ToByteArray());

                var msq = new NetMQMessage();
                msq.Append(envelope);
                msq.Append(body);

                socket.SendMessage(msq);

                var responseMsg = socket.ReceiveMessage();

                return(SerializationMethods.FromByteArray <TResponse>(responseMsg[3].Buffer));
            }
        }
コード例 #26
0
        private static void awaitClients(DealerSocket input, int clients, Dictionary <string, DealerSocket> result, NetMQContext context, IDistributedApp app)
        {
            while (result.Count < clients)
            {
                var clientCmd = input.ReceiveFrameString();
                var json      = JObject.Parse(clientCmd) as dynamic;

                string clientUrl = json.Url;

                //connect
                var socket = context.CreateDealerSocket();
                socket.Connect(clientUrl);
                result[clientUrl] = socket;

                //register instances
                var instances = (json.Instances as JArray)
                                .Select(val => Guid.Parse(val.ToString()));

                foreach (var id in instances)
                {
                    app.RemoteInstance(id, msg => writeMessage(socket, msg));
                }
            }
        }
コード例 #27
0
        public void CancelSocket()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                // we are using three responses to make sure we actually move the correct socket and other sockets still work
                using (var router = contex.CreateRouterSocket())
                    using (var router2 = contex.CreateRouterSocket())
                        using (var router3 = contex.CreateRouterSocket())
                        {
                            router.Bind("tcp://127.0.0.1:5002");
                            router2.Bind("tcp://127.0.0.1:5003");
                            router3.Bind("tcp://127.0.0.1:5004");

                            using (var dealer = contex.CreateDealerSocket())
                                using (var dealer2 = contex.CreateDealerSocket())
                                    using (var dealer3 = contex.CreateDealerSocket())
                                        using (Poller poller = new Poller())
                                        {
                                            dealer.Connect("tcp://127.0.0.1:5002");
                                            dealer2.Connect("tcp://127.0.0.1:5003");
                                            dealer3.Connect("tcp://127.0.0.1:5004");

                                            bool first = true;

                                            router2.ReceiveReady += (s, a) =>
                                            {
                                                bool more;

                                                // identity
                                                byte[] identity = a.Socket.Receive(out more);

                                                // message
                                                a.Socket.Receive(out more);

                                                a.Socket.SendMore(identity);
                                                a.Socket.Send("2");
                                            };

                                            poller.AddSocket(router2);

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

                                                bool more;

                                                // identity
                                                a.Socket.Receive(out more);

                                                string m = a.Socket.ReceiveString(out more);

                                                Assert.False(more);
                                                Assert.AreEqual("Hello", m);

                                                // cancellign the socket
                                                poller.RemoveSocket(a.Socket);
                                            };

                                            poller.AddSocket(router);

                                            router3.ReceiveReady += (s, a) =>
                                            {
                                                bool more;

                                                // identity
                                                byte[] identity = a.Socket.Receive(out more);

                                                // message
                                                a.Socket.Receive(out more);

                                                a.Socket.SendMore(identity).Send("3");
                                            };

                                            poller.AddSocket(router3);

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

                                            dealer.Send("Hello");

                                            // sending this should not arrive on the poller, therefore response for this will never arrive
                                            dealer.Send("Hello2");

                                            Thread.Sleep(100);

                                            // sending this should not arrive on the poller, therefore response for this will never arrive
                                            dealer.Send("Hello3");

                                            Thread.Sleep(500);

                                            bool more2;

                                            // making sure the socket defined before the one cancelled still works
                                            dealer2.Send("1");
                                            string msg = dealer2.ReceiveString(out more2);
                                            Assert.AreEqual("2", msg);

                                            // making sure the socket defined after the one cancelled still works
                                            dealer3.Send("1");
                                            msg = dealer3.ReceiveString(out more2);
                                            Assert.AreEqual("3", msg);

                                            // we have to give this some time if we want to make sure it's really not happening and it not only because of time
                                            Thread.Sleep(300);

                                            poller.Stop();

                                            Thread.Sleep(100);
                                            Assert.IsTrue(pollerTask.IsCompleted);
                                        }
                        }
            }
        }
コード例 #28
0
        public void AddTwoSocketAfterRemoving()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                // we are using three responses to make sure we actually move the correct socket and other sockets still work
                using (var router = contex.CreateRouterSocket())
                    using (var router2 = contex.CreateRouterSocket())
                        using (var router3 = contex.CreateRouterSocket())
                            using (var router4 = contex.CreateRouterSocket())
                            {
                                router.Bind("tcp://127.0.0.1:5002");
                                router2.Bind("tcp://127.0.0.1:5003");
                                router3.Bind("tcp://127.0.0.1:5004");
                                router4.Bind("tcp://127.0.0.1:5005");

                                using (var dealer = contex.CreateDealerSocket())
                                    using (var dealer2 = contex.CreateDealerSocket())
                                        using (var dealer3 = contex.CreateDealerSocket())
                                            using (var dealer4 = contex.CreateDealerSocket())
                                                using (Poller poller = new Poller())
                                                {
                                                    dealer.Connect("tcp://127.0.0.1:5002");
                                                    dealer2.Connect("tcp://127.0.0.1:5003");
                                                    dealer3.Connect("tcp://127.0.0.1:5004");
                                                    dealer4.Connect("tcp://127.0.0.1:5005");


                                                    int  router1arrived = 0;
                                                    int  router2arrived = 0;
                                                    bool router3arrived = false;
                                                    bool router4arrived = false;

                                                    bool more;

                                                    router.ReceiveReady += (s, a) =>
                                                    {
                                                        router1arrived++;

                                                        router.Receive(out more);
                                                        router.Receive(out more);

                                                        poller.RemoveSocket(router);
                                                    };

                                                    poller.AddSocket(router);

                                                    router3.ReceiveReady += (s, a) =>
                                                    {
                                                        router3.Receive(out more);
                                                        router3.Receive(out more);
                                                        router3arrived = true;
                                                    };

                                                    router4.ReceiveReady += (s, a) =>
                                                    {
                                                        router4.Receive(out more);
                                                        router4.Receive(out more);
                                                        router4arrived = true;
                                                    };

                                                    router2.ReceiveReady += (s, a) =>
                                                    {
                                                        router2arrived++;
                                                        router2.Receive(out more);
                                                        router2.Receive(out more);

                                                        if (router2arrived == 1)
                                                        {
                                                            poller.AddSocket(router3);

                                                            poller.AddSocket(router4);
                                                        }
                                                    };

                                                    poller.AddSocket(router2);

                                                    Task task = Task.Factory.StartNew(poller.Start);

                                                    dealer.Send("1");
                                                    Thread.Sleep(300);
                                                    dealer2.Send("2");
                                                    Thread.Sleep(300);
                                                    dealer3.Send("3");
                                                    dealer4.Send("4");
                                                    dealer2.Send("2");
                                                    dealer.Send("1");
                                                    Thread.Sleep(300);

                                                    poller.Stop(true);
                                                    task.Wait();

                                                    router.Receive(true, out more);

                                                    Assert.IsTrue(more);

                                                    router.Receive(true, out more);

                                                    Assert.IsFalse(more);

                                                    Assert.AreEqual(1, router1arrived);
                                                    Assert.AreEqual(2, router2arrived);
                                                    Assert.IsTrue(router3arrived);
                                                    Assert.IsTrue(router4arrived);
                                                }
                            }
            }
        }
コード例 #29
0
        public void SimpleTimer()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                // we are using three responses to make sure we actually move the correct socket and other sockets still work
                using (var router = contex.CreateRouterSocket())
                {
                    router.Bind("tcp://127.0.0.1:5002");

                    using (var dealer = contex.CreateDealerSocket())
                        using (Poller poller = new Poller())
                        {
                            dealer.Connect("tcp://127.0.0.1:5002");


                            bool messageArrived = false;

                            router.ReceiveReady += (s, a) =>
                            {
                                bool isMore;
                                router.Receive(out isMore);
                                router.Receive(out isMore);


                                messageArrived = true;
                            };

                            poller.AddSocket(router);

                            bool timerTriggered = false;

                            int count = 0;

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

                            poller.PollTillCancelledNonBlocking();

                            Thread.Sleep(150);

                            dealer.Send("hello");

                            Thread.Sleep(300);

                            poller.CancelAndJoin();

                            Assert.IsTrue(messageArrived);
                            Assert.IsTrue(timerTriggered);
                            Assert.AreEqual(1, count);
                        }
                }
            }
        }
コード例 #30
0
        public void AddSocketAfterRemoving()
        {
            using (NetMQContext contex = NetMQContext.Create())
            {
                // we are using three responses to make sure we actually move the correct socket and other sockets still work
                using (var router = contex.CreateRouterSocket())
                    using (var router2 = contex.CreateRouterSocket())
                        using (var router3 = contex.CreateRouterSocket())
                        {
                            router.Bind("tcp://127.0.0.1:5002");
                            router2.Bind("tcp://127.0.0.1:5003");
                            router3.Bind("tcp://127.0.0.1:5004");

                            using (var dealer = contex.CreateDealerSocket())
                                using (var dealer2 = contex.CreateDealerSocket())
                                    using (var dealer3 = contex.CreateDealerSocket())
                                        using (Poller poller = new Poller())
                                        {
                                            dealer.Connect("tcp://127.0.0.1:5002");
                                            dealer2.Connect("tcp://127.0.0.1:5003");
                                            dealer3.Connect("tcp://127.0.0.1:5004");

                                            bool router1arrived = false;
                                            bool router2arrived = false;
                                            bool router3arrived = false;


                                            bool more;

                                            router.ReceiveReady += (s, a) =>
                                            {
                                                router1arrived = true;

                                                router.Receive(out more);
                                                router.Receive(out more);

                                                poller.RemoveSocket(router);
                                            };

                                            poller.AddSocket(router);

                                            router3.ReceiveReady += (s, a) =>
                                            {
                                                router3.Receive(out more);
                                                router3.Receive(out more);
                                                router3arrived = true;
                                            };

                                            router2.ReceiveReady += (s, a) =>
                                            {
                                                router2arrived = true;
                                                router2.Receive(out more);
                                                router2.Receive(out more);

                                                poller.AddSocket(router3);
                                            };
                                            poller.AddSocket(router2);

                                            poller.PollTillCancelledNonBlocking();

                                            dealer.Send("1");
                                            Thread.Sleep(300);
                                            dealer2.Send("2");
                                            Thread.Sleep(300);
                                            dealer3.Send("3");
                                            Thread.Sleep(300);

                                            poller.Stop(true);

                                            Assert.IsTrue(router1arrived);
                                            Assert.IsTrue(router2arrived);
                                            Assert.IsTrue(router3arrived);
                                        }
                        }
            }
        }
コード例 #31
0
        /// <summary>
        /// Tries to connect to the QDMS server.
        /// </summary>
        public void Connect()
        {
            Dispose();

            _context      = NetMQContext.Create();
            _reqSocket    = _context.CreateDealerSocket();
            _subSocket    = _context.CreateSubscriberSocket();
            _dealerSocket = _context.CreateSocket(ZmqSocketType.Dealer);

            _reqSocket.Options.Identity    = Encoding.UTF8.GetBytes(_name);
            _subSocket.Options.Identity    = Encoding.UTF8.GetBytes(_name);
            _dealerSocket.Options.Identity = Encoding.UTF8.GetBytes(_name);

            _dealerSocket.ReceiveReady += _dealerSocket_ReceiveReady;
            _reqSocket.ReceiveReady    += _reqSocket_ReceiveReady;
            _subSocket.ReceiveReady    += _subSocket_ReceiveReady;

            _reqSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort));

            //start off by sending a ping to make sure everything is regular
            string reply = "";

            try
            {
                _reqSocket.SendMore("");
                _reqSocket.Send("PING");

                _reqSocket.ReceiveString(TimeSpan.FromSeconds(1)); //empty frame starts the REP message //todo receive string?
                reply = _reqSocket.ReceiveString(TimeSpan.FromMilliseconds(50));
            }
            catch
            {
                Dispose();
            }


            if (reply != "PONG") //server didn't reply or replied incorrectly
            {
                _reqSocket.Disconnect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort));
                _reqSocket.Close();
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Could not connect to server."));
                    return;
                }
            }

            _lastHeartBeat = DateTime.Now;
            _subSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimePublishPort));
            _dealerSocket.Connect(string.Format("tcp://{0}:{1}", _host, _historicalDataPort));

            _running = true;

            //this loop sends out historical data requests and receives the data
            _dealerLoopThread = new Thread(DealerLoop)
            {
                Name = "Client Dealer Loop"
            };
            _dealerLoopThread.Start();

            //this loop takes care of replies to the request socket: heartbeats and data request status messages
            _poller = new Poller();
            _poller.AddSocket(_reqSocket);
            _poller.AddSocket(_subSocket);
            _poller.AddSocket(_dealerSocket);
            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);

            _heartBeatTimer          = new Timer(1000);
            _heartBeatTimer.Elapsed += _timer_Elapsed;
            _heartBeatTimer.Start();
        }