Beispiel #1
0
            public void Run()
            {
                Options opts = CreateClientOptions(clientName, tlsKey, password);

                opts.ReconnectedEventHandler += (sender, args) =>
                {
                    Console.WriteLine("Client {0} reconnected.", clientName);
                    Reconnected = true;
                };

                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    Console.WriteLine("Client {0} connected.", clientName);

                    EventHandler <MsgHandlerEventArgs> msgHandler = (sender, cbArgs) =>
                    {
                        //NOOP
                    };

                    using (IAsyncSubscription s = c.SubscribeAsync(subject, msgHandler))
                    {
                        // Go ahead and keep a thread up for stressing the system a bit.
                        while (true)
                        {
                            // always up
                            Thread.Sleep(250);
                        }
                    }
                }
            }
Beispiel #2
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);
        }
        private NATSObservableSubscription(IAsyncSubscription subscription)
        {
            this.subscription = subscription ?? throw new ArgumentNullException(nameof(subscription));

            this.subscription.MessageHandler += OnIncomingMessage;
            this.subscription.Start();
        }
Beispiel #4
0
        public void TestEncodedSerizationOverrides()
        {
            using (IEncodedConnection c = new ConnectionFactory().CreateEncodedConnection())
            {
                c.OnDeserialize = deserializeFromXML;
                c.OnSerialize   = serializeToXML;

                Object mu = new Object();
                SerializationTestObj origObj = new SerializationTestObj();
                origObj.a = 99;

                EventHandler <EncodedMessageEventArgs> eh = (sender, args) =>
                {
                    SerializationTestObj so = (SerializationTestObj)args.ReceivedObject;
                    Assert.IsTrue(so.Equals(origObj));

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

                using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                {
                    lock (mu)
                    {
                        c.Publish("foo", origObj);
                        c.Flush();

                        Monitor.Wait(mu, 1000);
                    }
                }
            }
        }
Beispiel #5
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.");
                    }
                }
            }
        }
Beispiel #6
0
        /// <inheritdoc />
        public Task Start(RequestDelegate requestDelegate, CancellationToken cancellationToken)
        {
            var connection = _connection.CreateConnection(_options.Options);

            _log.LogTrace("NATS connected. Subscribing to queue {host}", _options.Server.Host);

            _subscription = connection.SubscribeAsync(_options.Server.Host, async(_, args) =>
            {
                try
                {
                    var context = await _converter.Parse(args, new FeatureCollection());

                    if (context != null)
                    {
                        await requestDelegate(context);
                        await _responseProcessed.ProcessResponse(args, context, connection);
                    }
                    else
                    {
                        _log.LogError("Cannot parse context");
                    }
                }
                catch (Exception e)
                {
                    _log.LogError(e, $"Nats server not processed request {args.Message.Subject}");
                }
            });

            _log.LogTrace("NATS server subscribed");
            return(Task.CompletedTask);
        }
Beispiel #7
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");
                    }
                }
            }
        }
Beispiel #8
0
        public void TestEncodedObjectRequestReply()
        {
            using (new NATSServer())
            {
                using (IEncodedConnection c = DefaultEncodedConnection)
                {
                    c.OnDeserialize = jsonDeserializer;
                    c.OnSerialize   = jsonSerializer;

                    JsonObject origObj = new JsonObject("foo");

                    EventHandler <EncodedMessageEventArgs> eh = (sender, args) =>
                    {
                        JsonObject so = (JsonObject)args.ReceivedObject;
                        Assert.True(so.Equals(origObj));

                        c.Publish(args.Reply, new JsonObject("Received"));
                        c.Flush();
                    };

                    using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                    {
                        var jo = (JsonObject)c.Request("foo", origObj, 1000);
                        Assert.Equal("Received", jo.Value);

                        jo = (JsonObject)c.Request("foo", origObj, 1000);
                        Assert.Equal("Received", jo.Value);
                    }
                }
            }
        }
Beispiel #9
0
        private Task <QueryNatsAdapter> GetResponse(IEncodedConnection connection, string replySubj,
                                                    out IAsyncSubscription subscription)
        {
            var promise   = new TaskCompletionSource <QueryNatsAdapter>();
            var completed = 0;
            var waitTime  = 0;

            ThreadPool.QueueUserWorkItem(data =>
            {
                while (completed == 0)
                {
                    if (waitTime >= 60)
                    {
                        promise.SetException(new Exception("Nats connection timeout exceed"));
                        break;
                    }

                    Thread.Sleep(1000);
                    waitTime++;
                }
            });

            subscription = connection.SubscribeAsync(replySubj,
                                                     (sender, args) =>
            {
                var result = (QueryNatsAdapter)args.ReceivedObject;
                promise.SetResult(result);
                completed++;
            });

            return(promise.Task);
        }
Beispiel #10
0
        public void TestEncodedSerizationOverrides()
        {
            using (new NATSServer())
            {
                using (IEncodedConnection c = DefaultEncodedConnection)
                {
                    c.OnDeserialize = jsonDeserializer;
                    c.OnSerialize   = jsonSerializer;

                    AutoResetEvent ev = new AutoResetEvent(false);

                    JsonObject origObj = new JsonObject("bar");

                    EventHandler <EncodedMessageEventArgs> eh = (sender, args) =>
                    {
                        JsonObject so = (JsonObject)args.ReceivedObject;
                        Assert.True(so.Equals(origObj));

                        ev.Set();
                    };

                    using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                    {
                        c.Publish("foo", origObj);
                        c.Flush();

                        ev.WaitOne(1000);
                    }
                }
            }
        }
Beispiel #11
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();
        }
Beispiel #12
0
        public void TestAsyncSubHandlerAPI()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    int received = 0;

                    EventHandler <MsgHandlerEventArgs> h = (sender, args) =>
                    {
                        Interlocked.Increment(ref received);
                    };

                    using (IAsyncSubscription s = c.SubscribeAsync("foo", h))
                    {
                        c.Publish("foo", null);
                        c.Flush();
                        Thread.Sleep(500);
                    }

                    using (IAsyncSubscription s = c.SubscribeAsync("foo", "bar", h))
                    {
                        c.Publish("foo", null);
                        c.Flush();
                        Thread.Sleep(500);
                    }

                    Assert.Equal(2, received);
                }
            }
        }
Beispiel #13
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.");
                    }
                }
            }
        }
Beispiel #14
0
        void runPubSub(String testName, long testCount, long testSize)
        {
            Object pubSubLock = new Object();
            bool   finished   = false;
            int    subCount   = 0;

            byte[] payload = generatePayload(testSize);

            ConnectionFactory cf = new ConnectionFactory();

            Options o = ConnectionFactory.GetDefaultOptions();

            o.Url = url;
            o.SubChannelLength        = 10000000;
            o.AsyncErrorEventHandler += (sender, obj) => {
                System.Console.WriteLine("Error: " + obj.Error);
            };

            IConnection subConn = cf.CreateConnection(o);
            IConnection pubConn = cf.CreateConnection(url);

            IAsyncSubscription s = subConn.SubscribeAsync(subject, (sender, args) =>
            {
                subCount++;
                if (subCount == testCount)
                {
                    lock (pubSubLock)
                    {
                        finished = true;
                        Monitor.Pulse(pubSubLock);
                    }
                }
            });

            s.SetPendingLimits(10000000, 1000000000);
            subConn.Flush();

            Stopwatch sw = Stopwatch.StartNew();

            for (int i = 0; i < testCount; i++)
            {
                pubConn.Publish(subject, payload);
            }

            pubConn.Flush();

            lock (pubSubLock)
            {
                if (!finished)
                {
                    Monitor.Wait(pubSubLock);
                }
            }
            sw.Stop();

            PrintResults(testName, sw, testCount, testSize);

            pubConn.Close();
            subConn.Close();
        }
Beispiel #15
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);
                    }
                }
            }
        }
Beispiel #16
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);
                }
            }
        }
Beispiel #17
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);
                    }
                }
            }
        }
Beispiel #18
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);
                }
            }
        }
Beispiel #19
0
        public void TestAsyncSubHandlerAPI()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                int received = 0;

                EventHandler <MsgHandlerEventArgs> h = (sender, args) =>
                {
                    Interlocked.Increment(ref received);
                };

                using (IAsyncSubscription s = c.SubscribeAsync("foo", h))
                {
                    c.Publish("foo", null);
                    c.Flush();
                    Thread.Sleep(500);
                }

                using (IAsyncSubscription s = c.SubscribeAsync("foo", "bar", h))
                {
                    c.Publish("foo", null);
                    c.Flush();
                    Thread.Sleep(500);
                }

                if (received != 2)
                {
                    Assert.Fail("Received ({0}) != 2", received);
                }
            }
        }
Beispiel #20
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);
                    }
                }
            }
        }
Beispiel #21
0
        public void TestDefaultObjectSerialization()
        {
            using (new NATSServer())
            {
                using (IEncodedConnection c = DefaultEncodedConnection)
                {
                    Object mu = new Object();
                    SerializationTestObj origObj = new SerializationTestObj();

                    EventHandler <EncodedMessageEventArgs> eh = (sender, args) =>
                    {
                        // Ensure we blow up in the cast
                        SerializationTestObj so = (SerializationTestObj)args.ReceivedObject;
                        Assert.True(so.Equals(origObj));

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

                    using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                    {
                        lock (mu)
                        {
                            c.Publish("foo", new SerializationTestObj());
                            c.Flush();

                            Monitor.Wait(mu, 1000);
                        }
                    }
                }
            }
        }
Beispiel #22
0
        public void TestEncodedObjectRequestReply()
        {
            using (IEncodedConnection c = new ConnectionFactory().CreateEncodedConnection())
            {
                Object mu = new Object();
                SerializationTestObj origObj = new SerializationTestObj();

                EventHandler <EncodedMessageEventArgs> eh = (sender, args) =>
                {
                    SerializationTestObj so = (SerializationTestObj)args.ReceivedObject;
                    Assert.IsTrue(so.Equals(origObj));
                    String str = "Received";

                    c.Publish(args.Reply, str);
                    c.Flush();

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

                using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                {
                    Assert.IsTrue("Received".Equals(c.Request("foo", origObj, 1000)));
                    Assert.IsTrue("Received".Equals(c.Request("foo", origObj)));
                }
            }
        }
Beispiel #23
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await WrapStarter(() => _connection = _connectionFactory.Get <QueryNatsAdapter>(), cancellationToken);

            var queue = _queueFactory.Get();

            _subscription = _connection.SubscribeAsync(queue, CreateHandler());
        }
Beispiel #24
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();
     }
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="backoffPolicy">The back off policy to use.</param>
 /// <param name="subscription">The suubscription to be processed</param>
 /// <param name="logger">The logger to use for reporting issues</param>
 protected AbstractBackoffSubscriptionProcessor(
     IAsyncBackoffPolicy backoffPolicy,
     IAsyncSubscription <T> subscription,
     ILogger <AbstractBackoffSubscriptionProcessor <T> > logger)
 {
     _backoffPolicy = backoffPolicy;
     _subscription  = subscription;
     _logger        = logger;
 }
Beispiel #27
0
        public void Receive <T>(string subject, IMessageHandler <T> handler) where T : class
        {
            CommonConsumer <T> consumer = new CommonConsumer <T>(handler);

            using (IEncodedConnection connector = _natsConnectorFactory.GetConnector(defaultNatsURL))
            {
                IAsyncSubscription s = connector.SubscribeAsync(subject, (sender, args) => { consumer.Process(args); });
            }
        }
Beispiel #28
0
 public void Stop()
 {
     if (subscription != null)
     {
         subscription.Dispose();
         subscription = null;
     }
     Resource.Service.With(Resource, closeCallback);
 }
Beispiel #29
0
        private static void SubscribeClear()
        {
            EventHandler <MsgHandlerEventArgs> handler = (sender, args) =>
            {
                Console.Clear();
            };

            IAsyncSubscription s = _connection.SubscribeAsync(
                "nats.demo.clear", handler);
        }
        private async Task MonitorProcess()
        {
            while (!_token.IsCancellationRequested)
            {
                try
                {
                    bool exSleep;
                    lock (_lock)
                        exSleep = _exceptionSleep;
                    if (exSleep)
                    {
                        OnDispose();
                        Core.Log.Warning("An exception has been thrown, the listener has been stoped for {0} seconds.", Config.RequestOptions.ServerReceiverOptions.SleepOnExceptionInSec);
                        await Task.Delay(Config.RequestOptions.ServerReceiverOptions.SleepOnExceptionInSec * 1000, _token).ConfigureAwait(false);

                        lock (_lock)
                            _exceptionSleep = false;
                        _connection.Close();
                        _receiver.Unsubscribe();
                        _connection = _factory.CreateConnection(Connection.Route);
                        _receiver   = _connection.SubscribeAsync(Connection.Name, MessageHandler);
                        Core.Log.Warning("The listener has been resumed.");
                    }

                    if (Counters.CurrentMessages >= Config.RequestOptions.ServerReceiverOptions.MaxSimultaneousMessagesPerQueue)
                    {
                        OnDispose();
                        Core.Log.Warning("Maximum simultaneous messages per queue has been reached, the message needs to wait to be processed, consider increase the MaxSimultaneousMessagePerQueue value, CurrentValue={0}.", Config.RequestOptions.ServerReceiverOptions.MaxSimultaneousMessagesPerQueue);

                        while (!_token.IsCancellationRequested && Counters.CurrentMessages >= Config.RequestOptions.ServerReceiverOptions.MaxSimultaneousMessagesPerQueue)
                        {
                            await Task.Delay(500, _token).ConfigureAwait(false);
                        }

                        _connection.Close();
                        _receiver.Unsubscribe();
                        _connection = _factory.CreateConnection(Connection.Route);
                        _receiver   = _connection.SubscribeAsync(Connection.Name, MessageHandler);
                        Core.Log.Warning("The listener has been resumed.");
                    }

                    await Task.Delay(100, _token).ConfigureAwait(false);
                }
                catch (TaskCanceledException) { }
                catch (Exception ex)
                {
                    Core.Log.Write(ex);
                    if (!_token.IsCancellationRequested)
                    {
                        await Task.Delay(2000, _token).ConfigureAwait(false);
                    }
                }
            }
        }
Beispiel #31
0
        public void TestAsyncSubscribe()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                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);
                    }

                    if (!received)
                        Assert.Fail("Did not receive message.");
                }
            }
        }
Beispiel #32
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);
            }
        }