Exemplo n.º 1
0
        public void TestSendAndRecv()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    int received = 0;
                    int count    = 1000;

                    s.MessageHandler += (sender, args) =>
                    {
                        Interlocked.Increment(ref received);
                    };

                    s.Start();

                    for (int i = 0; i < count; i++)
                    {
                        c.Publish("foo", null);
                    }
                    c.Flush();

                    Thread.Sleep(500);

                    if (received != count)
                    {
                        Assert.Fail("Received ({0}) != count ({1})", received, count);
                    }
                }
            }
        }
Exemplo n.º 2
0
        public void Run()
        {
            _subscription = _connection.SubscribeAsync(Const.RankProcess, "rank_calculator", (sender, args) =>
            {
                var id      = Encoding.UTF8.GetString(args.Message.Data);
                var textKey = Const.TextTitleKey + id;

                if (!_redisStorage.IsKeyExist(textKey))
                {
                    _logger.LogWarning("Text key {textKey} doesn't exists", textKey);
                    return;
                }

                var text    = _redisStorage.Load(textKey);
                var rankKey = Const.RankTitleKey + id;
                var rank    = CalculateRank(text).ToString();

                _redisStorage.Store(rankKey, rank);

                string message = $"Event: RankCalculated, context id: {id}, rank: {rank}";
                _connection.Publish(Const.BrokerRank, Encoding.UTF8.GetBytes(message));
            });

            _subscription.Start();

            Console.WriteLine("Press Enter to exit (RankCalculator)");
            Console.ReadLine();

            _subscription.Unsubscribe();

            _connection.Drain();
            _connection.Close();
        }
Exemplo n.º 3
0
        public void TestServerAutoUnsub()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    long received = 0;
                    int  max      = 10;

                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        s.MessageHandler += (sender, arg) =>
                        {
                            received++;
                        };

                        s.AutoUnsubscribe(max);
                        s.Start();

                        for (int i = 0; i < (max * 2); i++)
                        {
                            c.Publish("foo", Encoding.UTF8.GetBytes("hello"));
                        }
                        c.Flush();

                        Thread.Sleep(500);

                        Assert.Equal(max, received);

                        Assert.False(s.IsValid);
                    }
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        ///  消息订阅
        /// </summary>
        /// <returns></returns>
        public bool Subscribe(string topic)
        {
            bool succeed = false;

            try
            {
                if (CheckConnect())
                {
                    EventHandler <MsgHandlerEventArgs> h = (sender, args) =>
                    {
                        byte[] data = args.Message.Data;
                        string msg  = Encoding.UTF8.GetString(data);
                        _Callback(msg);
                        // print the message
                        //Console.WriteLine(args.Message);
                    };

                    IAsyncSubscription sAsync = _conn.SubscribeAsync(topic);
                    sAsync.MessageHandler += h;
                    sAsync.Start();
                    sAsyncList.Add(topic, sAsync);
                    succeed = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(typeof(RemoteInfoHelper).FullName, "消息服务订阅消息异常..." + ex.Message);
            }
            return(succeed);
        }
Exemplo n.º 5
0
        public void TestServerAutoUnsub()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                long received = 0;
                int  max      = 10;

                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    s.MessageHandler += (sender, arg) =>
                    {
                        System.Console.WriteLine("Received msg.");
                        received++;
                    };

                    s.AutoUnsubscribe(max);
                    s.Start();

                    for (int i = 0; i < (max * 2); i++)
                    {
                        c.Publish("foo", Encoding.UTF8.GetBytes("hello"));
                    }
                    c.Flush();

                    Thread.Sleep(500);

                    if (received != max)
                    {
                        Assert.Fail("Recieved ({0}) != max ({1})",
                                    received, max);
                    }
                    Assert.IsFalse(s.IsValid);
                }
            }
        }
Exemplo n.º 6
0
        public void TestRequest()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        byte[] response = Encoding.UTF8.GetBytes("I will help you.");

                        s.MessageHandler += (sender, args) =>
                        {
                            c.Publish(args.Message.Reply, response);
                            c.Flush();
                        };

                        s.Start();

                        Msg m = c.Request("foo", Encoding.UTF8.GetBytes("help."),
                                          5000);

                        Assert.True(compare(m.Data, response), "Response isn't valid");
                    }
                }
            }
        }
Exemplo n.º 7
0
        public void TestAsyncSubscribe()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        asyncSub          = s;
                        s.MessageHandler += CheckReceivedAndValidHandler;
                        s.Start();

                        lock (mu)
                        {
                            received = false;
                            c.Publish("foo", omsg);
                            c.Flush();
                            Monitor.Wait(mu, 30000);
                        }

                        Assert.True(received, "Did not receive message.");
                    }
                }
            }
        }
Exemplo n.º 8
0
        public void TestRequest()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    byte[] response = Encoding.UTF8.GetBytes("I will help you.");

                    s.MessageHandler += (sender, args) =>
                    {
                        c.Publish(args.Message.Reply, response);
                        c.Flush();
                    };

                    s.Start();

                    Msg m = c.Request("foo", Encoding.UTF8.GetBytes("help."),
                                      5000);

                    if (!compare(m.Data, response))
                    {
                        Assert.Fail("Response isn't valid");
                    }
                }
            }
        }
Exemplo n.º 9
0
        public void TestAsyncSubscribe()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    asyncSub          = s;
                    s.MessageHandler += CheckRecveivedAndValidHandler;
                    s.Start();

                    lock (mu)
                    {
                        received = false;
                        c.Publish("foo", omsg);
                        c.Flush();
                        Monitor.Wait(mu, 30000);
                    }

                    if (!received)
                    {
                        Assert.Fail("Did not receive message.");
                    }
                }
            }
        }
Exemplo n.º 10
0
        public void TestServerAutoUnsub()
        {
            using (NATSServer.CreateFastAndVerify(Context.Server1.Port))
            {
                using (IConnection c = Context.OpenConnection(Context.Server1.Port))
                {
                    long received = 0;
                    int  max      = 10;

                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        s.MessageHandler += (sender, arg) =>
                        {
                            received++;
                        };

                        s.AutoUnsubscribe(max);
                        s.Start();

                        for (int i = 0; i < (max * 2); i++)
                        {
                            c.Publish("foo", Encoding.UTF8.GetBytes("hello"));
                        }
                        c.Flush();

                        Thread.Sleep(500);

                        Assert.Equal(max, received);

                        Assert.False(s.IsValid);
                    }
                }
            }
        }
Exemplo n.º 11
0
        public void TestFlushInHandler()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        byte[] response = Encoding.UTF8.GetBytes("I will help you.");

                        s.MessageHandler += (sender, args) =>
                        {
                            c.Flush();

                            lock (mu)
                            {
                                Monitor.Pulse(mu);
                            }
                        };

                        s.Start();

                        lock (mu)
                        {
                            c.Publish("foo", Encoding.UTF8.GetBytes("Hello"));
                            Monitor.Wait(mu);
                        }
                    }
                }
            }
        }
Exemplo n.º 12
0
        public void TestBasicReconnectFunctionality()
        {
            Options opts = Context.GetTestOptions(Context.Server1.Port);

            opts.MaxReconnect  = 2;
            opts.ReconnectWait = 1000;

            Object testLock = new Object();
            Object msgLock  = new Object();

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                lock (testLock)
                {
                    Monitor.Pulse(testLock);
                }
            };

            opts.ReconnectedEventHandler = (sender, args) =>
            {
                // NOOP
            };

            NATSServer ns = NATSServer.Create(Context.Server1.Port);

            using (IConnection c = Context.ConnectionFactory.CreateConnection(opts))
            {
                IAsyncSubscription s = c.SubscribeAsync("foo");
                s.MessageHandler += (sender, args) =>
                {
                    lock (msgLock)
                    {
                        Monitor.Pulse(msgLock);
                    }
                };

                s.Start();
                c.Flush();

                lock (testLock)
                {
                    ns.Shutdown();
                    Assert.True(Monitor.Wait(testLock, 100000));
                }

                c.Publish("foo", Encoding.UTF8.GetBytes("Hello"));

                // restart the server.
                using (ns = NATSServer.Create(Context.Server1.Port))
                {
                    lock (msgLock)
                    {
                        c.Flush(50000);
                        Assert.True(Monitor.Wait(msgLock, 10000));
                    }

                    Assert.True(c.Stats.Reconnects == 1);
                }
            }
        }
Exemplo n.º 13
0
        public void TestSendAndRecv()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        int received = 0;
                        int count    = 1000;

                        s.MessageHandler += (sender, args) =>
                        {
                            Interlocked.Increment(ref received);
                        };

                        s.Start();

                        for (int i = 0; i < count; i++)
                        {
                            c.Publish("foo", null);
                        }
                        c.Flush();

                        Thread.Sleep(500);

                        Assert.Equal(count, received);
                    }
                }
            }
        }
Exemplo n.º 14
0
        public void TestSlowAsyncSubscriber()
        {
            AutoResetEvent ev = new AutoResetEvent(false);

            Options opts = utils.DefaultTestOptions;

            opts.SubChannelLength = 100;

            using (new NATSServer())
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        Object mu = new Object();

                        s.MessageHandler += (sender, args) =>
                        {
                            // block to back us up.
                            ev.WaitOne(2000);
                        };

                        s.Start();

                        Assert.True(s.PendingByteLimit == Defaults.SubPendingBytesLimit);
                        Assert.True(s.PendingMessageLimit == Defaults.SubPendingMsgsLimit);

                        long pml = 100;
                        long pbl = 1024 * 1024;

                        s.SetPendingLimits(pml, pbl);

                        Assert.True(s.PendingByteLimit == pbl);
                        Assert.True(s.PendingMessageLimit == pml);

                        for (int i = 0; i < (pml + 100); i++)
                        {
                            c.Publish("foo", null);
                        }

                        int flushTimeout = 5000;

                        Stopwatch sw = new Stopwatch();
                        sw.Start();

                        c.Flush(flushTimeout);

                        sw.Stop();

                        ev.Set();

                        Assert.False(sw.ElapsedMilliseconds >= flushTimeout,
                                     string.Format("elapsed ({0}) > timeout ({1})",
                                                   sw.ElapsedMilliseconds, flushTimeout));
                    }
                }
            }
        }
 public void Subscribe(EventHandler <MsgHandlerEventArgs> handler, IEnumerable <string> listOfTopics)
 {
     foreach (var topic in listOfTopics)
     {
         _asyncSubscription = _connection.SubscribeAsync(topic);
         _asyncSubscription.MessageHandler += handler;
         _asyncSubscription.Start();
     }
 }
Exemplo n.º 16
0
        public void Run()
        {
            _subscription.Start();

            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();

            _connection.Drain();
            _connection.Close();
        }
Exemplo n.º 17
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     connection = natsConnection.GetConnection();
     logger.LogInformation("---------------------------------------------------------------");
     logger.LogInformation("-->Connecting to natssamplestream...");
     subscription = connection.SubscribeAsync("natssamplestream.samplesubject.timestamp.received.>");
     subscription.MessageHandler += SubscriptionArrived;
     logger.LogInformation("-->Connected to natssamplestream!");
     logger.LogInformation("---------------------------------------------------------------");
     subscription.Start();
     return(Task.CompletedTask);
 }
Exemplo n.º 18
0
        public void TestUnsubscribe()
        {
            int count = 0;
            int max   = 20;

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    Boolean unsubscribed = false;
                    asyncSub = s;
                    //s.MessageHandler += UnsubscribeAfterCount;
                    s.MessageHandler += (sender, args) =>
                    {
                        count++;
                        System.Console.WriteLine("Count = {0}", count);
                        if (count == max)
                        {
                            asyncSub.Unsubscribe();
                            lock (mu)
                            {
                                unsubscribed = true;
                                Monitor.Pulse(mu);
                            }
                        }
                    };
                    s.Start();

                    max = 20;
                    for (int i = 0; i < max; i++)
                    {
                        c.Publish("foo", null, null);
                    }
                    Thread.Sleep(100);
                    c.Flush();

                    lock (mu)
                    {
                        if (!unsubscribed)
                        {
                            Monitor.Wait(mu, 5000);
                        }
                    }
                }

                if (count != max)
                {
                    Assert.Fail("Received wrong # of messages after unsubscribe: {0} vs {1}", count, max);
                }
            }
        }
Exemplo n.º 19
0
        public void TestLargeSubjectAndReply()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                String subject = "";
                for (int i = 0; i < 1024; i++)
                {
                    subject += "A";
                }

                String reply = "";
                for (int i = 0; i < 1024; i++)
                {
                    reply += "A";
                }

                using (IAsyncSubscription s = c.SubscribeAsync(subject))
                {
                    Object testLock = new Object();

                    s.MessageHandler += (sender, args) =>
                    {
                        if (!subject.Equals(args.Message.Subject))
                        {
                            Assert.Fail("Invalid subject received.");
                        }

                        if (!reply.Equals(args.Message.Reply))
                        {
                            Assert.Fail("Invalid subject received.");
                        }

                        lock (testLock)
                        {
                            Monitor.Pulse(testLock);
                        }
                    };

                    s.Start();

                    c.Publish(subject, reply, null);
                    c.Flush();

                    lock (testLock)
                    {
                        Assert.IsTrue(Monitor.Wait(testLock, 1000));
                    }
                }
            }
        }
Exemplo n.º 20
0
        public void TestUnsubscribe()
        {
            int count = 0;
            int max   = 20;

            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        Boolean unsubscribed = false;
                        asyncSub = s;
                        //s.MessageHandler += UnsubscribeAfterCount;
                        s.MessageHandler += (sender, args) =>
                        {
                            count++;
                            if (count == max)
                            {
                                asyncSub.Unsubscribe();
                                lock (mu)
                                {
                                    unsubscribed = true;
                                    Monitor.Pulse(mu);
                                }
                            }
                        };
                        s.Start();

                        max = 20;
                        for (int i = 0; i < max; i++)
                        {
                            c.Publish("foo", null, null);
                        }
                        Thread.Sleep(100);
                        c.Flush();

                        lock (mu)
                        {
                            if (!unsubscribed)
                            {
                                Monitor.Wait(mu, 5000);
                            }
                        }
                    }

                    Assert.Equal(max, count);
                }
            }
        }
 public static IObservable <MsgHandlerEventArgs> ToObservable(this IAsyncSubscription sub)
 {
     return(Observable.Create <MsgHandlerEventArgs>(
                observer =>
     {
         EventHandler <MsgHandlerEventArgs> handler = (sender, args) => observer.OnNext(args);
         sub.MessageHandler += handler;
         sub.Start();
         return Disposable.Create(() =>
         {
             sub.MessageHandler -= handler;
             sub.Unsubscribe();
         });
     }));
 }
Exemplo n.º 22
0
        public void TestLargeSubjectAndReply()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    String subject = "";
                    for (int i = 0; i < 1024; i++)
                    {
                        subject += "A";
                    }

                    String reply = "";
                    for (int i = 0; i < 1024; i++)
                    {
                        reply += "A";
                    }

                    // 1 MB
                    byte[] data = new byte[1 << 20];

                    using (IAsyncSubscription s = c.SubscribeAsync(subject))
                    {
                        AutoResetEvent ev        = new AutoResetEvent(false);
                        string         recvSubj  = null;
                        string         recvReply = null;

                        s.MessageHandler += (sender, args) =>
                        {
                            recvSubj  = args.Message.Subject;
                            recvReply = args.Message.Reply;

                            ev.Set();
                        };

                        s.Start();

                        c.Publish(subject, reply, data);
                        c.Flush();

                        Assert.True(ev.WaitOne(10000));
                        Assert.Equal(subject, recvSubj);
                        Assert.Equal(reply, recvReply);
                    }
                }
            }
        }
Exemplo n.º 23
0
        public void TestAsyncSubscriberStarvation()
        {
            Object waitCond = new Object();

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription helper = c.SubscribeAsync("helper"),
                       start = c.SubscribeAsync("start"))
                {
                    helper.MessageHandler += (sender, arg) =>
                    {
                        System.Console.WriteLine("Helper");
                        c.Publish(arg.Message.Reply,
                                  Encoding.UTF8.GetBytes("Hello"));
                    };
                    helper.Start();

                    start.MessageHandler += (sender, arg) =>
                    {
                        System.Console.WriteLine("Responsder");
                        string             responseIB = c.NewInbox();
                        IAsyncSubscription ia         = c.SubscribeAsync(responseIB);

                        ia.MessageHandler += (iSender, iArgs) =>
                        {
                            System.Console.WriteLine("Internal subscriber.");
                            lock (waitCond) { Monitor.Pulse(waitCond); }
                        };
                        ia.Start();

                        c.Publish("helper", responseIB,
                                  Encoding.UTF8.GetBytes("Help me!"));
                    };

                    start.Start();

                    c.Publish("start", Encoding.UTF8.GetBytes("Begin"));
                    c.Flush();

                    lock (waitCond)
                    {
                        Assert.IsTrue(Monitor.Wait(waitCond, 2000));
                    }
                }
            }
        }
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _subscription = _connection.SubscribeAsync(nameof(VoteCreated));
            _subscription.MessageHandler += async(sender, args) =>
            {
                var obj = JsonConvert.DeserializeObject <VoteCreated>(Encoding.UTF8.GetString(args.Message.Data));
                using (var scope = _scopeFactory.CreateScope())
                {
                    var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();
                    await mediator.Send(new AddVoteCommand(obj.SubjectId, obj.OptionName));
                }
            };

            _subscription.Start();

            return(Task.CompletedTask);
        }
Exemplo n.º 25
0
        private TimeSpan receiveAsyncSubscriber(IConnection c)
        {
            Stopwatch sw = new Stopwatch();

            using (IAsyncSubscription s = c.SubscribeAsync(subject))
            {
                Object testLock = new Object();

                s.MessageHandler += (sender, args) =>
                {
                    if (received == 0)
                    {
                        sw.Start();
                    }

                    received++;

                    if (verbose)
                    {
                        Console.WriteLine("Received: " + args.Message);
                    }

                    replyMsg.Subject = args.Message.Reply;
                    c.Publish(replyMsg);

                    if (received >= count)
                    {
                        sw.Stop();
                        lock (testLock)
                        {
                            Monitor.Pulse(testLock);
                        }
                    }
                };

                lock (testLock)
                {
                    s.Start();
                    Monitor.Wait(testLock);
                }
            }

            return(sw.Elapsed);
        }
Exemplo n.º 26
0
        public void TestAsyncSubscriberStarvation()
        {
            AutoResetEvent ev = new AutoResetEvent(false);

            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription helper = c.SubscribeAsync("helper"),
                           start = c.SubscribeAsync("start"))
                    {
                        helper.MessageHandler += (sender, arg) =>
                        {
                            c.Publish(arg.Message.Reply,
                                      Encoding.UTF8.GetBytes("Hello"));
                        };
                        helper.Start();

                        start.MessageHandler += (sender, arg) =>
                        {
                            string             responseIB = c.NewInbox();
                            IAsyncSubscription ia         = c.SubscribeAsync(responseIB);

                            ia.MessageHandler += (iSender, iArgs) =>
                            {
                                ev.Set();
                            };
                            ia.Start();

                            c.Publish("helper", responseIB,
                                      Encoding.UTF8.GetBytes("Help me!"));
                        };

                        start.Start();

                        c.Publish("start", Encoding.UTF8.GetBytes("Begin"));
                        c.Flush();

                        Assert.True(ev.WaitOne(10000));
                    }
                }
            }
        }
Exemplo n.º 27
0
        public void TestAsyncSubscribersOnClose()
        {
            /// basically tests if the subscriber sub channel gets
            /// cleared on a close.
            Object waitCond  = new Object();
            int    callbacks = 0;

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    s.MessageHandler += (sender, args) =>
                    {
                        callbacks++;
                        lock (waitCond)
                        {
                            Monitor.Wait(waitCond);
                        }
                    };

                    s.Start();

                    for (int i = 0; i < 10; i++)
                    {
                        c.Publish("foo", null);
                    }
                    c.Flush();

                    Thread.Sleep(500);
                    c.Close();

                    lock (waitCond)
                    {
                        Monitor.Pulse(waitCond);
                    }

                    Thread.Sleep(500);

                    Assert.IsTrue(callbacks == 1);
                }
            }
        }
Exemplo n.º 28
0
        public void TestLargeMessage()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    int    msgSize = 51200;
                    byte[] msg     = new byte[msgSize];

                    for (int i = 0; i < msgSize; i++)
                    {
                        msg[i] = (byte)'A';
                    }

                    msg[msgSize - 1] = (byte)'Z';

                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        Object testLock = new Object();

                        s.MessageHandler += (sender, args) =>
                        {
                            lock (testLock)
                            {
                                Monitor.Pulse(testLock);
                            }
                            Assert.True(compare(msg, args.Message.Data));
                        };

                        s.Start();

                        c.Publish("foo", msg);
                        c.Flush(1000);

                        lock (testLock)
                        {
                            Monitor.Wait(testLock, 2000);
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
        public void TestStats()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    byte[] data = Encoding.UTF8.GetBytes("The quick brown fox jumped over the lazy dog");
                    int    iter = 10;

                    for (int i = 0; i < iter; i++)
                    {
                        c.Publish("foo", data);
                    }
                    c.Flush(1000);

                    IStatistics stats = c.Stats;
                    Assert.Equal(iter, stats.OutMsgs);
                    Assert.Equal(iter * data.Length, stats.OutBytes);

                    c.ResetStats();

                    // Test both sync and async versions of subscribe.
                    IAsyncSubscription s1 = c.SubscribeAsync("foo");
                    s1.MessageHandler += (sender, arg) => { };
                    s1.Start();

                    ISyncSubscription s2 = c.SubscribeSync("foo");

                    for (int i = 0; i < iter; i++)
                    {
                        c.Publish("foo", data);
                    }
                    c.Flush(1000);

                    stats = c.Stats;
                    Assert.Equal(2 * iter, stats.InMsgs);
                    Assert.Equal(2 * iter * data.Length, stats.InBytes);
                }
            }
        }
Exemplo n.º 30
0
        public void TestAsyncSubscribersOnClose()
        {
            /// basically tests if the subscriber sub channel gets
            /// cleared on a close.
            AutoResetEvent ev        = new AutoResetEvent(false);
            int            callbacks = 0;

            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                    {
                        s.MessageHandler += (sender, args) =>
                        {
                            callbacks++;
                            ev.WaitOne(10000);
                        };

                        s.Start();

                        for (int i = 0; i < 10; i++)
                        {
                            c.Publish("foo", null);
                        }
                        c.Flush();

                        Thread.Sleep(500);
                        c.Close();

                        ev.Set();

                        Thread.Sleep(500);

                        Assert.True(callbacks == 1);
                    }
                }
            }
        }