Esempio n. 1
0
        public void ContructorShouldReturnMDPClientAsync()
        {
            var address = "tcp://localhost:5555";
            var session = new MDPClientAsync(address);

            Assert.That(session, Is.Not.Null);
            Assert.That(session.Address, Is.EqualTo(address));
            Assert.That(session.Timeout, Is.EqualTo(TimeSpan.FromMilliseconds(10000)));

            session.Dispose();
        }
Esempio n. 2
0
        public void ReceiveMessageFailedIfWasNotProcessed()
        {
            const string hostAddress = "tcp://localhost:5555";
            var loggingMessages = new List<string>();
            var serviceName = "echo";
            Guid requestId = Guid.Empty;

            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    // doesn't reply to client
                    var msg = e.Socket.ReceiveMultipartMessage();
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    Assert.IsTrue(false, "I'm not supposed to receive replies since broker is not sending them");
                    poller.Stop();
                };
                session.FailedRequest += (s, e) =>
                {
                    Assert.That(requestId, Is.Not.EqualTo(Guid.Empty));
                    Assert.That(e.RequestId, Is.EqualTo(requestId));
                    poller.Stop();
                };

                poller.Add(broker);
                var task = Task.Factory.StartNew(() => poller.Run());

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });

                requestId = session.Send(serviceName, requestMessage);
                var result = task.Wait(session.Timeout + session.Timeout);
                Assert.IsTrue(result, $"During {session.Timeout}ms was not received a FailedReply");
            }
        }
Esempio n. 3
0
        public void ReconnectToBrokerIfIsNotReplying()
        {
            const string hostAddress = "tcp://localhost:5555";
            const int timeOutToReconnectInMillis = 7500;
            var loggingMessages = new List<string>();
            var serviceName = "echo";
            var messagesReceivedOnBroker = 0;

            // setup the counter socket for communication
            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                session.Timeout = TimeSpan.FromMilliseconds(timeOutToReconnectInMillis);
                broker.Bind(hostAddress);
                broker.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    if (messagesReceivedOnBroker != 0) // doesn't respond if is the first message received!
                    {
                        // we expect to receive a 4 Frame message
                        // [client adrR][e][mdp header][service][request]
                        if (msg.FrameCount != 6)
                            Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                        // REQUEST socket will strip the his address + empty frame
                        // ROUTER has to add the address prelude in order to identify the correct socket(!)

                        var requestId = msg.Last.ConvertToString(); // get the requestId string
                        msg.RemoveFrame(msg.Last); // remove the request frame

                        var request = msg.Last.ConvertToString(); // get the request string
                        msg.RemoveFrame(msg.Last); // remove the request frame

                        msg.Append(new NetMQFrame(request + " OK")); // append the reply frame
                        msg.Append(requestId);
                        e.Socket.SendMultipartMessage(msg);
                    }
                    messagesReceivedOnBroker++;
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    var reply = e.Reply;

                    Assert.That(reply.FrameCount, Is.EqualTo(1));
                    Assert.That(reply.First.ConvertToString(), Is.EqualTo("REQUEST OK"));

                    poller.Stop();
                };

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });

                int timeOutInMillis = timeOutToReconnectInMillis + 3000; // Waits for the timeOut on the client
                var timer = new NetMQTimer(timeOutInMillis);
                timer.Elapsed += (s, e) =>
                {
                    session.Send(serviceName, requestMessage); // resends the request after timeout
                };

                poller.Add(timer);
                poller.Add(broker);
                var task = Task.Factory.StartNew(() => poller.Run());

                session.Send(serviceName, requestMessage);

                var result = task.Wait(timeOutToReconnectInMillis * 2);

                var numberOfConnects = loggingMessages.FindAll(x => x.Contains("[CLIENT] connecting to broker")).Count;
                Assert.IsTrue(numberOfConnects > 1);
            }
        }
Esempio n. 4
0
        public void SendWrongMDPVersionFromBrokerNoLoggingShouldThrowApplicationException()
        {
            const string hostAddress = "tcp://localhost:5555";

            // setup the counter socket for communication
            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    // return empty reply
                    var msg = e.Socket.ReceiveMultipartMessage();
                    // we expect to receive a 4 Frame message
                    // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"][requestId]
                    if (msg.FrameCount != 6)
                        Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                    // REQUEST socket will strip the his address + empty frame
                    // ROUTER has to add the address prelude in order to identify the correct socket(!)
                    // [REQ ADR][EMPTY]["MDPC00"]["echo"]["REQUEST"][requestId]
                    var clientAddress = msg.Pop();
                    msg.Pop(); // forget empty frame
                    msg.Pop(); // drop the MDP Version Frame
                    msg.Push("MDPC00"); // insert wrong MDP version
                    msg.Push(NetMQFrame.Empty);
                    msg.Push(clientAddress); // reinsert the client's address

                    e.Socket.SendMultipartMessage(msg);
                };

                int timeOutInMillis = 10000;
                var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong!
                timer.Elapsed += (s, e) =>
                {
                    Assert.Fail($"Waited {timeOutInMillis} and had no response from broker");
                    poller.Stop();
                };

                poller.Add(broker);
                poller.Add(timer);

                session.ReplyReady += (s, e) =>
                {
                    Assert.True(e.HasError());
                    Assert.That(e.Exception.Message, Is.StringContaining("MDP Version mismatch"));
                    poller.Stop(); // To unlock the Task.Wait()
                };

                session.FailedRequest += (s, e) =>
                {
                    Assert.True(e.HasError());
                    Assert.That(e.Exception.Message, Is.StringContaining("MDP Version mismatch"));
                    poller.Stop(); // To unlock the Task.Wait()
                };

                var task = Task.Factory.StartNew(() => poller.Run());

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                session.Send("echo", requestMessage);

                task.Wait();
            }
        }
Esempio n. 5
0
        public void SendWithSpaceServiceNameWithLoggingShouldThrowApplicationException()
        {
            const string hostAddress = "tcp://localhost:5555";
            var loggingMessages = new List<string>();

            // setup the counter socket for communication
            using (var session = new MDPClientAsync(hostAddress))
            {
                // set the event handler to receive the logging messages
                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                try
                {
                    session.Send("  ", requestMessage);
                }
                catch (ApplicationException ex)
                {
                    Assert.That(ex.Message, Is.EqualTo("serviceName must not be empty or null."));
                }

                Assert.That(loggingMessages.Count, Is.EqualTo(0));
            }
        }
Esempio n. 6
0
        public void SendEmptyReplyFromBrokerWithLoggingShouldThrowApplicationException()
        {
            const string hostAddress = "tcp://localhost:5555";
            var loggingMessages = new List<string>();

            // setup the counter socket for communication
            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    // return empty reply
                    var msg = e.Socket.ReceiveMultipartMessage();
                    // we expect to receive a 4 Frame message
                    // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"][requestId]
                    if (msg.FrameCount != 6)
                        Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                    // REQUEST socket will strip the his address + empty frame
                    // ROUTER has to add the address prelude in order to identify the correct socket(!)
                    // [REQ ADR][EMPTY]["MDPC01"]["echo"]["REQUEST"][requestId]

                    e.Socket.SendMultipartMessage(msg);
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    Assert.That(loggingMessages.Count, Is.EqualTo(3));
                    Assert.That(loggingMessages[0], Is.EqualTo("[CLIENT] connecting to broker at tcp://localhost:5555"));
                    Assert.That(loggingMessages[1].Contains("[CLIENT INFO] sending"), Is.True);
                    Assert.That(loggingMessages[2].Contains("[CLIENT INFO] received"), Is.True);

                    poller.Stop(); // To unlock the Task.Wait()
                };

                poller.Add(broker);
                var task = Task.Factory.StartNew(() => poller.Run());
                // well formed message
                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });
                // correct call
                session.Send("echo", requestMessage);

                int timeOutInMillis = 10000;
                var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong!
                timer.Elapsed += (s, e) =>
                {
                    Assert.Fail($"Waited {timeOutInMillis} and had no response from broker");
                    poller.Stop();
                };

                poller.Add(timer);
                task.Wait();
            }
        }
Esempio n. 7
0
        public void SendCorrectInputWithLoggingShouldReturnCorrectReply()
        {
            const string hostAddress = "tcp://localhost:5555";
            var loggingMessages = new List<string>();
            var serviceName = "echo";

            using (var broker = new RouterSocket())
            using (var poller = new NetMQPoller())
            using (var session = new MDPClientAsync(hostAddress))
            {
                broker.Bind(hostAddress);
                // we need to pick up any message in order to avoid errors
                broker.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    // we expect to receive a 4 Frame message
                    // [client adrR][e][mdp header][service][request]
                    if (msg.FrameCount != 6)
                        Assert.Fail("Message with wrong count of frames {0}", msg.FrameCount);
                    // REQUEST socket will strip the his address + empty frame
                    // ROUTER has to add the address prelude in order to identify the correct socket(!)
                    // [client adr][e][mdp header][service][reply][requestId]

                    var requestId = msg.Last.ConvertToString(); // get the requestId string
                    msg.RemoveFrame(msg.Last); // remove the request frame

                    var request = msg.Last.ConvertToString(); // get the request string
                    msg.RemoveFrame(msg.Last); // remove the request frame

                    msg.Append(new NetMQFrame(request + " OK")); // append the reply frame
                    msg.Append(requestId);
                    e.Socket.SendMultipartMessage(msg);
                };

                session.LogInfoReady += (s, e) => loggingMessages.Add(e.Info);
                session.ReplyReady += (s, e) =>
                {
                    var reply = e.Reply;

                    Assert.That(reply.FrameCount, Is.EqualTo(1));
                    Assert.That(reply.First.ConvertToString(), Is.EqualTo("REQUEST OK"));

                    poller.Stop();
                };
                int timeOutInMillis = 10000;
                var timer = new NetMQTimer(timeOutInMillis); // Used so it doesn't block if something goes wrong!
                timer.Elapsed += (s, e) =>
                {
                    Assert.Fail($"Waited {timeOutInMillis} and had no response from broker");
                    poller.Stop();
                };

                poller.Add(broker);
                poller.Add(timer);
                var task = Task.Factory.StartNew(() => poller.Run());

                var requestMessage = new NetMQMessage(new[] { new NetMQFrame("REQUEST") });

                session.Send(serviceName, requestMessage);

                task.Wait();

                Assert.That(loggingMessages.Count, Is.EqualTo(3));
                Assert.That(loggingMessages[0], Is.EqualTo("[CLIENT] connecting to broker at tcp://localhost:5555"));
                Assert.That(loggingMessages[1].Contains("[CLIENT INFO] sending"), Is.True);
                Assert.That(loggingMessages[2].Contains("[CLIENT INFO] received"), Is.True);
            }
        }
        /// <summary>
        ///     usage:  MDPClientAsyncExample [-v] [-rn] (1 ;lt n ;lt 100000 / Default == 10)
        /// 
        ///     implements a MDPClientAsync API usage
        /// </summary>
        private static void Main(string[] args)
        {
            if (args.Length == 1 || args.Length > 2)
            {
                if (!(args[0] == "-v" || args[0].Contains("-r")))
                {
                    Console.WriteLine("MDPClientExample [-v(erbose) OR -h(elp)]");
                    Console.WriteLine("\t-v => verbose");
                    Console.WriteLine("\tto stop processing use CTRL+C");

                    return;
                }
            }

            const string service_name = "echo";
            const int max_runs = 100000;

            bool verbose = false;
            int runs = 10;

            if (args.Length >= 1)
            {
                if (args.Length == 1 && args[0] == "-v")
                    verbose = true;
                else if (args.Length == 2)
                    verbose = args[0] == "-v" || args[1] == "-v";

                if (args[0].Contains("-r") || args.Length > 1)
                {
                    if (args[0].Contains("-r"))
                        runs = GetInt(args[0]);
                    else if (args[1].Contains("-r"))
                        runs = GetInt(args[1]);
                }
            }

            runs = runs == -1 ? 10 : runs > max_runs ? max_runs : runs;

            var id = new[] { (byte)'C', (byte)'1' };

            var watch = new Stopwatch();

            Console.WriteLine("Starting MDPClient and will send {0} requests to service <{1}>.", runs, service_name);
            Console.WriteLine("(writes '.' for every 100 and '|' for every 1000 requests)\n");

            try
            {
                // create MDP client and set verboseness && use automatic disposal
                using (var session = new MDPClientAsync("tcp://localhost:5555", id))
                {

                    if (verbose)
                        session.LogInfoReady += (s, e) => Console.WriteLine("{0}", e.Info);

                    session.ReplyReady += (s, e) => Console.WriteLine("{0}", e.Reply);

                    // just give everything time to settle in
                    Thread.Sleep(500);

                    watch.Start();

                    for (int count = 0; count < runs; count++)
                    {
                        var request = new NetMQMessage();
                        // set the request data
                        request.Push("Hello World!");
                        // send the request to the service
                        session.Send(service_name, request);

                        if (count % 1000 == 0)
                            Console.Write("|");
                        else
                            if (count % 100 == 0)
                            Console.Write(".");
                    }

                    watch.Stop();
                    Console.Write("\nStop receiving with any key!");
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR:");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);

                return;
            }

            var time = watch.Elapsed;

            Console.WriteLine("{0} request/replies in {1} ms processed! Took {2:N3} ms per REQ/REP",
                runs,
                time.TotalMilliseconds,
                time.TotalMilliseconds / runs);

            Console.Write("\nExit with any key!");
            Console.ReadKey();
        }