Ejemplo n.º 1
0
        public void TestSubDelTaskCountWithSyncSub()
        {
            var opts = utils.DefaultTestOptions;

            opts.SubscriberDeliveryTaskCount = 1;

            using (new NATSServer())
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    ISyncSubscription s = c.SubscribeSync("foo");
                    c.Publish("foo", null);
                    s.NextMessage(10000);
                }
            }
        }
Ejemplo n.º 2
0
        public void TestSubDelTaskCountWithSyncSub()
        {
            var opts = Context.GetTestOptions(Context.Server1.Port);

            opts.SubscriberDeliveryTaskCount = 1;

            using (NATSServer.CreateFastAndVerify(Context.Server1.Port))
            {
                using (IConnection c = Context.ConnectionFactory.CreateConnection(opts))
                {
                    ISyncSubscription s = c.SubscribeSync("foo");
                    c.Publish("foo", null);
                    s.NextMessage(10000);
                }
            }
        }
Ejemplo n.º 3
0
        public void TestNextMessageOnClosedSub()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                ISyncSubscription s = c.SubscribeSync("foo");
                s.Unsubscribe();

                try
                {
                    s.NextMessage();
                }
                catch (NATSBadSubscriptionException) { } // ignore.

                // any other exceptions will fail the test.
            }
        }
Ejemplo n.º 4
0
 private static void SubscribePubSub()
 {
     Task.Run(() =>
     {
         ISyncSubscription sub = _connection.SubscribeSync("nats.demo.pubsub");
         while (!_exit)
         {
             var message = sub.NextMessage();
             if (message != null)
             {
                 string data = Encoding.UTF8.GetString(message.Data);
                 LogMessage(data);
             }
         }
     });
 }
Ejemplo n.º 5
0
        async Task runReqReplyAsync(string testName, long testCount, long testSize)
        {
            byte[] payload = generatePayload(testSize);

            ConnectionFactory cf = new ConnectionFactory();

            var opts = ConnectionFactory.GetDefaultOptions();

            opts.Url = url;
            opts.UseOldRequestStyle = useOldRequestStyle;
            if (creds != null)
            {
                opts.SetUserCredentials(creds);
            }

            IConnection subConn = cf.CreateConnection(opts);
            IConnection pubConn = cf.CreateConnection(opts);

            Thread t = new Thread(() =>
            {
                ISyncSubscription s = subConn.SubscribeSync(subject);
                for (int i = 0; i < testCount; i++)
                {
                    Msg m = s.NextMessage();
                    subConn.Publish(m.Reply, payload);
                    subConn.Flush();
                }
            });

            t.IsBackground = true;
            t.Start();

            Thread.Sleep(1000);

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < testCount; i++)
            {
                await pubConn.RequestAsync(subject, payload).ConfigureAwait(false);
            }
            sw.Stop();

            PrintResults(testName, sw, testCount, testSize);

            pubConn.Close();
            subConn.Close();
        }
Ejemplo n.º 6
0
        public void TestSyncSubscriptionPending()
        {
            int total = 100;

            ConditionalObj subDoneCond     = new ConditionalObj();
            ConditionalObj startProcessing = new ConditionalObj();

            byte[] data = System.Text.Encoding.UTF8.GetBytes("0123456789");

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                ISyncSubscription s = c.SubscribeSync("foo");

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

                Assert.IsTrue(s.QueuedMessageCount == total);

                Assert.IsTrue((s.MaxPendingBytes == (data.Length * total)) ||
                              (s.MaxPendingBytes == (data.Length * total)));
                Assert.IsTrue((s.MaxPendingMessages == total) ||
                              (s.MaxPendingMessages == total));

                Assert.IsTrue(s.Delivered == 0);
                Assert.IsTrue(s.Dropped == 0);

                for (int i = 0; i < total; i++)
                {
                    s.NextMessage();
                }

                Assert.IsTrue(s.QueuedMessageCount == 0);

                Assert.IsTrue((s.MaxPendingBytes == (data.Length * total)) ||
                              (s.MaxPendingBytes == (data.Length * total)));
                Assert.IsTrue((s.MaxPendingMessages == total) ||
                              (s.MaxPendingMessages == total));

                Assert.IsTrue(s.Delivered == total);
                Assert.IsTrue(s.Dropped == 0);

                s.Unsubscribe();
            }
        }
Ejemplo n.º 7
0
        public void TestSyncSubscriptionPending()
        {
            int total = 100;

            byte[] data = Encoding.UTF8.GetBytes("0123456789");

            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    ISyncSubscription s = c.SubscribeSync("foo");

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

                    Assert.True(s.QueuedMessageCount == total);

                    Assert.True((s.MaxPendingBytes == (data.Length * total)) ||
                                (s.MaxPendingBytes == (data.Length * total)));
                    Assert.True((s.MaxPendingMessages == total) ||
                                (s.MaxPendingMessages == total));

                    Assert.True(s.Delivered == 0);
                    Assert.True(s.Dropped == 0);

                    for (int i = 0; i < total; i++)
                    {
                        s.NextMessage();
                    }

                    Assert.True(s.QueuedMessageCount == 0);

                    Assert.True((s.MaxPendingBytes == (data.Length * total)) ||
                                (s.MaxPendingBytes == (data.Length * total)));
                    Assert.True((s.MaxPendingMessages == total) ||
                                (s.MaxPendingMessages == total));

                    Assert.True(s.Delivered == total);
                    Assert.True(s.Dropped == 0);

                    s.Unsubscribe();
                }
            }
        }
Ejemplo n.º 8
0
        public void TestSyncReplyArg()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (ISyncSubscription s = c.SubscribeSync("foo"))
                {
                    c.Publish("foo", "bar", null);
                    c.Flush(30000);

                    Msg m = s.NextMessage(1000);
                    if ("bar".Equals(m.Reply) == false)
                    {
                        Assert.Fail("Expected \"bar\", received: " + m);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public void TestSyncReplyArg()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (ISyncSubscription s = c.SubscribeSync("foo"))
                    {
                        c.Publish("foo", "bar", null);
                        c.Flush(30000);

                        Msg m = s.NextMessage(1000);

                        Assert.Equal("bar", m.Reply);
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public void TestNextMessageOnClosedSub()
        {
            using (NATSServer.CreateFastAndVerify(Context.Server1.Port))
            {
                using (IConnection c = Context.OpenConnection(Context.Server1.Port))
                {
                    ISyncSubscription s = c.SubscribeSync("foo");
                    s.Unsubscribe();

                    try
                    {
                        s.NextMessage();
                    }
                    catch (NATSBadSubscriptionException) { } // ignore.

                    // any other exceptions will fail the test.
                }
            }
        }
Ejemplo n.º 11
0
        public void TestNextMessageOnClosedSub()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    ISyncSubscription s = c.SubscribeSync("foo");
                    s.Unsubscribe();

                    try
                    {
                        s.NextMessage();
                    }
                    catch (NATSBadSubscriptionException) { } // ignore.

                    // any other exceptions will fail the test.
                }
            }
        }
Ejemplo n.º 12
0
        // TODO [TestMethod]
        public void TestSlowSubscriber()
        {
            Options opts = ConnectionFactory.GetDefaultOptions();

            opts.SubChannelLength = 10;

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                using (ISyncSubscription s = c.SubscribeSync("foo"))
                {
                    for (int i = 0; i < (opts.SubChannelLength + 100); i++)
                    {
                        c.Publish("foo", null);
                    }

                    try
                    {
                        c.Flush();
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex);
                        if (ex.InnerException != null)
                        {
                            System.Console.WriteLine(ex.InnerException);
                        }

                        throw ex;
                    }

                    try
                    {
                        s.NextMessage();
                    }
                    catch (NATSSlowConsumerException)
                    {
                        return;
                    }
                    Assert.Fail("Did not receive an exception.");
                }
            }
        }
Ejemplo n.º 13
0
        void runReqReply(string testName, long testCount, long testSize)
        {
            byte[] payload = generatePayload(testSize);

            ConnectionFactory cf = new ConnectionFactory();

            var opts = ConnectionFactory.GetDefaultOptions();

            opts.Url = url;
            opts.UseOldRequestStyle = useOldRequestStyle;

            IConnection subConn = cf.CreateConnection(opts);
            IConnection pubConn = cf.CreateConnection(opts);

            Thread t = new Thread(() =>
            {
                ISyncSubscription s = subConn.SubscribeSync(subject);
                for (int i = 0; i < testCount; i++)
                {
                    Msg m = s.NextMessage();
                    subConn.Publish(m.Reply, payload);
                    subConn.Flush();
                }
            });

            t.Start();

            Thread.Sleep(1000);

            var sw = Stopwatch.StartNew();

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

            PrintResults(testName, sw, testCount, testSize);

            pubConn.Close();
            subConn.Close();
        }
Ejemplo n.º 14
0
        public void TestQueueSubscriber()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (ISyncSubscription s1 = c.SubscribeSync("foo", "bar"),
                           s2 = c.SubscribeSync("foo", "bar"))
                    {
                        c.Publish("foo", omsg);
                        c.Flush(1000);

                        Assert.Equal(1, s1.QueuedMessageCount + s2.QueuedMessageCount);

                        // Drain the messages.
                        try { s1.NextMessage(100); }
                        catch (NATSTimeoutException) { }

                        try { s2.NextMessage(100); }
                        catch (NATSTimeoutException) { }

                        int total = 1000;

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

                        Thread.Sleep(1000);

                        int r1 = s1.QueuedMessageCount;
                        int r2 = s2.QueuedMessageCount;

                        Assert.Equal(total, r1 + r2);

                        Assert.False(Math.Abs(r1 - r2) > total * .15, string.Format("Too much variance between {0} and {1}", r1, r2));
                    }
                }
            }
        }
Ejemplo n.º 15
0
        public void TestCloseSubRelease()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (ISyncSubscription s = c.SubscribeSync("foo"))
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    try
                    {
                        new Task(() => { Thread.Sleep(100); c.Close(); }).Start();
                        s.NextMessage(10000);
                    }
                    catch (Exception) { /* ignore */ }

                    sw.Stop();

                    Assert.IsTrue(sw.ElapsedMilliseconds < 10000);
                }
            }
        }
Ejemplo n.º 16
0
        public void TestTlsScheme()
        {
            using (NATSServer srv = NATSServer.CreateWithConfig(Context.Server1.Port, "tls.conf"))
            {
                // we can't call create secure connection w/ the certs setup as they are
                // so we'll override the validation callback
                Options opts = Context.GetTestOptions(Context.Server1.Port);
                opts.Url = $"tls://127.0.0.1:{Context.Server1.Port}";
                opts.TLSRemoteCertificationValidationCallback = verifyServerCert;

                using (IConnection c = Context.ConnectionFactory.CreateConnection(opts))
                {
                    using (ISyncSubscription s = c.SubscribeSync("foo"))
                    {
                        c.Publish("foo", null);
                        c.Flush();
                        Msg m = s.NextMessage();
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public void TestRespondFailsWithServerClosed()
        {
            IConnection       c = null;
            ISyncSubscription s = null;

            try
            {
                Msg m;
                using (NATSServer ns = new NATSServer())
                {
                    Options options = utils.DefaultTestOptions;
                    options.AllowReconnect = false;

                    c = new ConnectionFactory().CreateConnection(options);
                    s = c.SubscribeSync("foo");

                    string replyTo = c.NewInbox();

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

                    m = s.NextMessage(1000);
                    Assert.NotNull(m);
                    Assert.Equal(replyTo, m.Reply);

                    ns.Shutdown();
                }

                // Give the server time to close
                Thread.Sleep(2000);

                byte[] reply = Encoding.UTF8.GetBytes("reply");
                Assert.ThrowsAny <NATSConnectionClosedException>(() => m.Respond(reply));
            }
            finally
            {
                c?.Dispose();
                s?.Dispose();
            }
        }
Ejemplo n.º 18
0
        void runReqReply(string testName, long testCount, long testSize)
        {
            Object pubSubLock = new Object();

            byte[] payload = generatePayload(testSize);

            ConnectionFactory cf = new ConnectionFactory();

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

            Thread t = new Thread(() => {
                ISyncSubscription s = subConn.SubscribeSync(subject);
                for (int i = 0; i < testCount; i++)
                {
                    Msg m = s.NextMessage();
                    subConn.Publish(m.Reply, payload);
                    subConn.Flush();
                }
            });

            t.Start();

            Thread.Sleep(1000);

            Stopwatch sw = sw = Stopwatch.StartNew();

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

            sw.Stop();

            PrintResults(testName, sw, testCount, testSize);

            pubConn.Close();
            subConn.Close();
        }
Ejemplo n.º 19
0
        public void TestTlsSuccessSecureConnect()
        {
            using (NATSServer srv = util.CreateServerWithConfig("tls_1222.conf"))
            {
                // we can't call create secure connection w/ the certs setup as they are
                // so we'll override the
                Options opts = util.DefaultTestOptions;
                opts.Secure = true;
                opts.TLSRemoteCertificationValidationCallback = verifyServerCert;
                opts.Url = "nats://localhost:1222";

                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    using (ISyncSubscription s = c.SubscribeSync("foo"))
                    {
                        c.Publish("foo", null);
                        c.Flush();
                        Msg m = s.NextMessage();
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public void TestClientAutoUnsub()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    long received = 0;
                    int  max      = 10;

                    using (ISyncSubscription s = c.SubscribeSync("foo"))
                    {
                        s.AutoUnsubscribe(max);

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

                        Thread.Sleep(100);

                        try
                        {
                            while (true)
                            {
                                s.NextMessage(0);
                                received++;
                            }
                        }
                        catch (NATSMaxMessagesException) { /* ignore */ }

                        Assert.True(received == max);
                        Assert.False(s.IsValid);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        public void TestRespondFailsWithClosedConnection()
        {
            using (NATSServer.CreateFastAndVerify(Context.Server1.Port))
            {
                using (IConnection c = Context.OpenConnection(Context.Server1.Port))
                {
                    ISyncSubscription s = c.SubscribeSync("foo");

                    string replyTo = c.NewInbox();
                    c.Publish("foo", replyTo, Encoding.UTF8.GetBytes("message"));

                    Msg m = s.NextMessage(1000);
                    Assert.NotNull(m);
                    Assert.Equal(replyTo, m.Reply);

                    c.Close();

                    byte[] reply = Encoding.UTF8.GetBytes("reply");
                    Assert.ThrowsAny <NATSConnectionClosedException>(() => m.Respond(reply));

                    s.Dispose();
                }
            }
        }
Ejemplo n.º 22
0
        public void TestCloseSubRelease()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    using (ISyncSubscription s = c.SubscribeSync("foo"))
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        try
                        {
                            new Task(() => { Thread.Sleep(100); c.Close(); }).Start();
                            s.NextMessage(10000);
                        }
                        catch (Exception) { /* ignore */ }

                        sw.Stop();

                        Assert.True(sw.ElapsedMilliseconds < 10000);
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public void TestCloseSubRelease()
        {
            using (NATSServer.CreateFastAndVerify(Context.Server1.Port))
            {
                using (IConnection c = Context.OpenConnection(Context.Server1.Port))
                {
                    using (ISyncSubscription s = c.SubscribeSync("foo"))
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        try
                        {
                            Task.Run(() => { Thread.Sleep(100); c.Close(); });
                            s.NextMessage(10000);
                        }
                        catch (Exception) { /* ignore */ }

                        sw.Stop();

                        Assert.True(sw.ElapsedMilliseconds < 10000);
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public void TestRespondFailsWithClosedConnection()
        {
            using (new NATSServer())
            {
                using (IConnection c = utils.DefaultTestConnection)
                {
                    ISyncSubscription s = c.SubscribeSync("foo");

                    string replyTo = c.NewInbox();
                    c.Publish("foo", replyTo, Encoding.UTF8.GetBytes("message"));

                    Msg m = s.NextMessage(1000);
                    Assert.NotNull(m);
                    Assert.Equal(replyTo, m.Reply);

                    c.Close();

                    byte[] reply = Encoding.UTF8.GetBytes("reply");
                    Assert.ThrowsAny <NATSConnectionClosedException>(() => m.Respond(reply));

                    s.Dispose();
                }
            }
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            GameInstance instance = new GameInstance();
            Options      opts     = ConnectionFactory.GetDefaultOptions();

            opts.Url    = "nats://demo.nats.io:4222";
            opts.Secure = false;
            string subject = "game" + args[0];

            Console.WriteLine("Sending on: " + subject);
            Console.WriteLine("Url is: " + args[1]);
            bool gameOver = false;

            if (args[1] != "null")
            {
                opts.Url = args[1];
            }

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                // c.Flush();
                using (ISyncSubscription s = c.SubscribeSync(subject + ".server"))
                {
                    instance.InitUsersAndGame(s, c, subject);
                    while (!gameOver)
                    {
                        Msg m = s.NextMessage();

                        GameEvent        ev         = JsonConvert.DeserializeObject <GameEvent>(Encoding.UTF8.GetString(m.Data));
                        List <GameEvent> sideEfects = new List <GameEvent>(instance.PlayMove(ev));
                        if (ev.Type == EvType.endTurn)
                        {
                            if (State.Instance.plOnMove == State.Instance.playerOne.IdUser)
                            {
                                foreach (Card item in State.Instance.playerTwoTable)
                                {
                                    item.Shield = State.Instance.playerTwoCards[item.IdCard].Shield;
                                }
                                State.Instance.plOnMove = State.Instance.playerTwo.IdUser;
                            }
                            else
                            {
                                foreach (Card item in State.Instance.playerOneTable)
                                {
                                    item.Shield = State.Instance.playerOneCards[item.IdCard].Shield;
                                }
                                State.Instance.plOnMove = State.Instance.PlayerOne.IdUser;
                            }
                            if (State.Instance.turn < 3)
                            {
                                State.Instance.playerCrystals = 0;
                            }
                            else if (State.Instance.turn < 5)
                            {
                                State.Instance.playerCrystals = 1;
                            }
                            else if (State.Instance.turn < 7)
                            {
                                State.Instance.playerCrystals = 2;
                            }
                            else if (State.Instance.turn < 12)
                            {
                                State.Instance.playerCrystals = 3;
                            }
                            State.Instance.playerGems = 8;
                            State.Instance.turn++;
                        }
                        else if (ev.Type == EvType.attack)
                        {
                            Card attacker      = null;
                            Card beingAttacked = null;;
                            if (State.Instance.plOnMove == State.Instance.playerOne.IdUser)
                            {
                                foreach (Card card in State.Instance.playerOneTable)
                                {
                                    if (card.IdCard == ev.Source)
                                    {
                                        attacker = card;
                                    }
                                }
                                foreach (Card card in State.Instance.playerTwoTable)
                                {
                                    if (card.IdCard == ev.Target)
                                    {
                                        beingAttacked = card;
                                    }
                                }
                                attacker.Shield -= beingAttacked.Attack <= attacker.Shield ? beingAttacked.Attack : attacker.Shield;
                                attacker.Health -= beingAttacked.Attack - attacker.Shield;
                                if (attacker.Health <= 0)
                                {
                                    State.Instance.playerOneTable.Remove(attacker);
                                    //TODO turi ga u groblje
                                }
                                beingAttacked.Shield -= attacker.Attack <= beingAttacked.Shield ? attacker.Attack : beingAttacked.Shield;
                                beingAttacked.Health -= attacker.Attack - beingAttacked.Shield;
                                if (beingAttacked.Health <= 0)
                                {
                                    State.Instance.playerTwoTable.Remove(beingAttacked);
                                    //TODO turi ga u groblje
                                }
                            }
                            else
                            {
                                foreach (Card card in State.Instance.playerOneTable)
                                {
                                    if (card.IdCard == ev.Source)
                                    {
                                        beingAttacked = card;
                                    }
                                }
                                foreach (Card card in State.Instance.playerTwoTable)
                                {
                                    if (card.IdCard == ev.Target)
                                    {
                                        attacker = card;
                                    }
                                }
                                attacker.Shield -= beingAttacked.Attack <= attacker.Shield ? beingAttacked.Attack : attacker.Shield;
                                attacker.Health -= beingAttacked.Attack - attacker.Shield;
                                if (attacker.Health <= 0)
                                {
                                    State.Instance.playerTwoTable.Remove(attacker);
                                    //TODO turi ga u groblje
                                }
                                beingAttacked.Shield -= attacker.Attack <= beingAttacked.Shield ? attacker.Attack : beingAttacked.Shield;
                                beingAttacked.Health -= attacker.Attack - beingAttacked.Shield;
                                if (beingAttacked.Health <= 0)
                                {
                                    State.Instance.playerOneTable.Remove(beingAttacked);
                                    //TODO turi ga u groblje
                                }
                            }
                        }
                        else if (ev.Type == EvType.attackPlayer)
                        {
                            Card attacker = null;
                            if (State.Instance.plOnMove == State.Instance.playerOne.IdUser)
                            {
                                foreach (Card card in State.Instance.playerOneTable)
                                {
                                    if (card.IdCard == ev.Source)
                                    {
                                        attacker = card;
                                    }
                                }
                                State.Instance.playerTwoLifePoints -= attacker.Attack;
                                if (State.Instance.playerTwoLifePoints <= 0)
                                {
                                    gameOver = true;
                                }
                            }
                            else
                            {
                                foreach (Card card in State.Instance.playerTwoTable)
                                {
                                    if (card.IdCard == ev.Source)
                                    {
                                        attacker = card;
                                    }
                                }
                                State.Instance.playerOneLifePoints -= attacker.Attack;
                                if (State.Instance.playerOneLifePoints <= 0)
                                {
                                    gameOver = true;
                                }
                            }
                        }
                        else if (ev.Type == EvType.surender)
                        {
                            if (State.Instance.plOnMove == State.Instance.playerOne.IdUser)
                            {
                                State.Instance.playerOneLifePoints = 0;
                            }
                            else
                            {
                                State.Instance.playerTwoLifePoints = 0;
                            }
                            gameOver = true;
                        }
                        else if (ev.Type == EvType.play)
                        {
                            if (ev.Source == State.Instance.plOnMove)
                            {
                                if (State.Instance.plOnMove == State.Instance.PlayerOne.IdUser)
                                {
                                    Card playd = new Card();
                                    foreach (var item in State.Instance.playerOneHand)
                                    {
                                        if (item.IdCard == ev.Target)
                                        {
                                            playd = item;
                                            break;
                                        }
                                    }
                                    if (State.Instance.playerGems >= playd.GemsCost && State.Instance.playerCrystals >= playd.CrystalsCost)
                                    {
                                        State.Instance.playerOneTable.Add(playd);
                                        State.Instance.playerOneHand.Remove(playd);
                                    }
                                }
                                else
                                {
                                    Card playd = new Card();
                                    foreach (var item in State.Instance.playerTwoHand)
                                    {
                                        if (item.IdCard == ev.Target)
                                        {
                                            playd = item;
                                            break;
                                        }
                                    }
                                    if (State.Instance.playerGems >= playd.GemsCost && State.Instance.playerCrystals >= playd.CrystalsCost)
                                    {
                                        State.Instance.playerTwoTable.Add(playd);
                                        State.Instance.playerTwoHand.Remove(playd);
                                    }
                                }
                            }
                        }
                        else if (ev.Type == EvType.spell)
                        {
                            Card spellCard;
                            if (State.Instance.plOnMove == State.Instance.playerOne.IdUser)
                            {
                                spellCard = State.Instance.playerOneCards[ev.Source];
                            }
                            else
                            {
                                spellCard = State.Instance.playerTwoCards[ev.Source];
                            }
                            instance.PlaySpellCard(spellCard, ev.Target);
                        }
                        //TODO dodaj obradu poruka/eventa
                        //ako je event tipa surender gameOver = true
                        //poslati poruku ko je pobednik
                        Console.WriteLine("original msg: " + m);
                        // Console.WriteLine("recived move: "+ Encoding.UTF8.GetString(m.Data));
                        c.Publish(subject, subject + ".server", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(State.Instance.CompressState())));

                        //TODO: provera da li neki player ima LP < 0
                    }

                    //u stanju pise ko je na potezu i to seproverava u unity-u
                    //dodati kod za updatovanje pobeda/gubitka korisnika u bazi i mmr-a
                }
            }
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            List <User>      matchUsers = new List <User>();
            Object           testLock   = new Object();
            Options          opts       = ConnectionFactory.GetDefaultOptions();
            ProcessStartInfo start;
            bool             found;
            long             matchId = 0;

            opts.Url    = "nats://demo.nats.io:4222";
            opts.Secure = false;
            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                // elapsed = receiveAsyncSubscriber(c);
                #region asyncConection
                // EventHandler<MsgHandlerEventArgs> msgHandler = (sender, args) =>
                // {
                //     Console.WriteLine("Received: " + System.Text.Encoding.UTF8.GetString(args.Message.Data));
                //     User recUser = JsonConvert.DeserializeObject<User>(System.Text.Encoding.UTF8.GetString(args.Message.Data));

                //     var msg = args.Message;
                //     found = false;
                //     foreach (var user in matchUsers)
                //     {
                //         if (recUser.WinNo + 20 > user.WinNo && recUser.WinNo - 15 < user.WinNo)
                //         {

                //             Match match = new Match(recUser, user, "null", matchId);//TODO: url brokera preko kog se razmenjuju poruke


                //             c.Publish(recUser.Rank, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(match)));
                //             c.Flush();

                //             matchUsers.Remove(user);
                //             found = true;

                //             start = new ProcessStartInfo();

                //             start.Arguments = matchId.ToString() + " null";
                //             //TODO: url brokera preko kog se razmenjuju poruke

                //             start.FileName = @"D:\ELFAK\IV godina\VII Semestar\Arhitektura I Projektovanje Softvera\Project\gameInstance\bin\Debug\netcoreapp3.1\gameInstance.exe";

                //             start.WindowStyle = ProcessWindowStyle.Hidden;
                //             start.CreateNoWindow = false;

                //             using (Process proc = Process.Start(start)) { }

                //             if (++matchId > 500000)
                //                 matchId = 0;

                //             break;
                //         }
                //     }
                //     if (!found)
                //     {
                //         matchUsers.Add(recUser);
                //     }
                //     // lock (testLock)
                //     // {
                //     //     Monitor.Pulse(testLock);
                //     // }
                //};
                #endregion

                using (ISyncSubscription s = c.SubscribeSync("matchs"))
                {
                    // just wait until we are done.
                    Msg m = new Msg();

                    while (true)
                    {
                        m = s.NextMessage();
                        Console.WriteLine("Received: " + System.Text.Encoding.UTF8.GetString(m.Data));
                        User recUser = JsonConvert.DeserializeObject <User>(System.Text.Encoding.UTF8.GetString(m.Data));

                        var msg = m;
                        found = false;
                        foreach (var user in matchUsers)
                        {
                            if (recUser.MMR + 20 > user.MMR && recUser.MMR - 15 < user.MMR)
                            {
                                Match match = new Match(recUser, user, "null", matchId);//TODO: url brokera preko kog se razmenjuju poruke


                                c.Publish(recUser.Region, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(match)));
                                c.Flush();

                                matchUsers.Remove(user);
                                found = true;

                                start = new ProcessStartInfo();

                                start.Arguments = matchId.ToString() + " null";
                                //TODO: url brokera preko kog se razmenjuju poruke

                                start.FileName = @"D:\ELFAK\IV godina\VII Semestar\Arhitektura I Projektovanje Softvera\Project\gameInstance\bin\Debug\netcoreapp3.1\gameInstance.exe";

                                start.WindowStyle    = ProcessWindowStyle.Hidden;
                                start.CreateNoWindow = false;

                                using (Process proc = Process.Start(start)) { }

                                if (++matchId > 500000)
                                {
                                    matchId = 0;
                                }

                                break;
                            }
                        }
                        if (!found)
                        {
                            matchUsers.Add(recUser);
                        }
                    }
                    // lock (testLock)
                    // {
                    //     Monitor.Pulse(testLock);
                    // }
                }


                //Console.Write("Received {0} msgs in {1} seconds ", received, elapsed.TotalSeconds);
            }
        }
Ejemplo n.º 27
0
        public async Task Run(string subject)
        {
            try
            {
                var cancelationTokenSource = new CancellationTokenSource();
                while (!cancelationTokenSource.Token.IsCancellationRequested)
                {
                    try
                    {
                        if (!IsConnected)
                        {
                            Reconnect(subject);
                        }

                        var responseMessage = JsonConvert.DeserializeObject <PublisherMessage>(System.Text.Encoding.Default.GetString(_subscription.NextMessage(1200).Data));
                        Console.WriteLine("Message has been received");
                        WriteMessageToDatabaseAsync(responseMessage);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
                _connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Ejemplo n.º 28
0
        public static void Main(string[] args)
        {
            ArgumentHelper helper = new ArgumentHelperBuilder("NATS JetStream Push Subscribe Bind Durable", args, Usage)
                                    .DefaultStream("fs-stream")
                                    .DefaultSubject("fs-subject")
                                    .Build();

            string subjectNoAck = helper.Subject + "noack";
            string subjectAck   = helper.Subject + "ack";
            string deliverNoAck = helper.DeliverSubject + "noack";
            string deliverAck   = helper.DeliverSubject + "ack";

            try
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(helper.MakeOptions()))
                {
                    // Create a JetStreamManagement context.
                    IJetStreamManagement jsm = c.CreateJetStreamManagementContext();

                    // Use the utility to create a stream stored in memory.
                    JsUtils.CreateStreamExitWhenExists(jsm, helper.Stream, subjectNoAck, subjectAck);

                    // Create our JetStream context.
                    IJetStream js = c.CreateJetStreamContext();

                    // The server uses the delivery subject as both an inbox for a JetStream subscription
                    // and as a core nats messages subject.
                    // BUT BE CAREFUL. THIS IS STILL A JETSTREAM SUBJECT AND ALL MESSAGES
                    // ADHERE TO THE ACK POLICY

                    // NoAck 1. Set up the noAck consumer / deliver subject configuration
                    ConsumerConfiguration cc = ConsumerConfiguration.Builder()
                                               .WithAckPolicy(AckPolicy.None)
                                               .WithAckWait(1000)
                                               .Build();

                    PushSubscribeOptions pso = PushSubscribeOptions.Builder()
                                               .WithDeliverSubject(deliverNoAck)
                                               .WithConfiguration(cc)
                                               .Build();

                    // NoAck 2. Set up the JetStream and core subscriptions
                    //          Notice the JetStream subscribes to the real subject
                    //          and the core subscribes to the delivery subject
                    //          Order matters, you must do the JetStream subscribe first
                    //          But you also must make sure the core sub is made
                    //          before messages are published
                    IJetStreamPushSyncSubscription jsSub = js.PushSubscribeSync(subjectNoAck, pso);
                    c.Flush(5000);
                    ISyncSubscription coreSub = c.SubscribeSync(deliverNoAck);

                    // NoAck 3. JsUtils.Publish to the real subject
                    JsUtils.Publish(js, subjectNoAck, "A", 1);

                    // NoAck 4. Read the message with the js no ack subscription. No need to ack
                    Msg msg = jsSub.NextMessage(1000);
                    PrintMessage("\nNoAck 4. Read w/JetStream sub", msg);

                    // NoAck 5. Read the message with the core subscription on the
                    //          no ack deliver subject. Since this message is a JetStream
                    //          message we could ack. But we don't have to since the consumer
                    //          was setup as AckPolicy None
                    msg = coreSub.NextMessage(1000);
                    PrintMessage("NoAck 5. Read w/core sub", msg);

                    // NoAck 6. Thread.Sleep longer than the ack wait period to check and make sure the
                    //     message is not replayed
                    Thread.Sleep(1100);

                    try
                    {
                        coreSub.NextMessage(1000);
                        Console.WriteLine("NoAck 6. NOPE! Should not have gotten here");
                    }
                    catch (NATSTimeoutException) // timeout means there are no messages available
                    {
                        Console.WriteLine("NoAck 6. Read w/core sub.\nAck Policy is none so no replay even though message was not Ack'd.\nThere was no message available.");
                    }

                    // Ack 1. Set up the Ack consumer / deliver subject configuration
                    cc = ConsumerConfiguration.Builder()
                         .WithAckPolicy(AckPolicy.Explicit)
                         .WithAckWait(1000)
                         .Build();

                    pso = PushSubscribeOptions.Builder()
                          .WithDeliverSubject(deliverAck)
                          .WithConfiguration(cc)
                          .Build();

                    // Ack 2. Set up the JetStream and core subscriptions
                    jsSub = js.PushSubscribeSync(subjectAck, pso);
                    c.Flush(5000);
                    coreSub = c.SubscribeSync(deliverAck);

                    // Ack 3. JsUtils.Publish to the real subject
                    JsUtils.Publish(js, subjectAck, "B", 1);

                    // Ack 4. Read the message with the js no ack subscription. No need to ack
                    msg = jsSub.NextMessage(1000);
                    PrintMessage("\nAck 4. Read w/JetStream sub", msg);

                    // Ack 5. Read the message with the core subscription on the
                    //        ack deliver subject.
                    //        Even though it is read on a core subscription
                    //        it still is a JetStream message. Don't ack this time
                    msg = coreSub.NextMessage(1000);
                    PrintMessage("Ack 5. Read w/core sub", msg);

                    // Ack 6. Thread.Sleep longer than the ack wait period to check and
                    //        see that the message is re-delivered. Ack this time.
                    Thread.Sleep(1100);
                    msg = coreSub.NextMessage(1000);
                    msg.Ack();
                    PrintMessage("Ack 6. Read w/core sub.\nWasn't Ack'd after step 'Ack 5.' so message was replayed.", msg);

                    // Ack 7. Thread.Sleep longer than the ack wait period. The message
                    //        is not re-delivered this time
                    Thread.Sleep(1100);

                    try
                    {
                        coreSub.NextMessage(1000);
                        Console.WriteLine("Ack 7. NOPE! Should not have gotten here");
                    }
                    catch (NATSTimeoutException) // timeout means there are no messages available
                    {
                        Console.WriteLine("Ack 7. Read w/core sub.\nMessage received by core sub in step 'Ack 6.' was JetStream so it was Ack'd and therefore not replayed.\nThere was no message available.", msg);
                    }

                    // delete the stream since we are done with it.
                    jsm.DeleteStream(helper.Stream);
                }
            }
            catch (Exception ex)
            {
                helper.ReportException(ex);
            }
        }