private TimeSpan receiveSyncSubscriber(IConnection c) { using (ISyncSubscription s = queueGroup == null?c.SubscribeSync(subject): c.SubscribeSync(subject, queueGroup)) { Stopwatch sw = new Stopwatch(); while (received < count) { if (received == 0) { sw.Start(); } Msg m = s.NextMessage(); received++; if (verbose) { Console.WriteLine("Received: " + m); } replyMsg.Subject = m.Reply; c.Publish(replyMsg); } sw.Stop(); return(sw.Elapsed); } }
public void TestRespondWithAutoUnsubscribe() { using (new NATSServer()) { using (IConnection c = utils.DefaultTestConnection) using (ISyncSubscription s = c.SubscribeSync("foo")) { s.AutoUnsubscribe(1); string replyTo = c.NewInbox(); using (ISyncSubscription r = c.SubscribeSync(replyTo)) { c.Publish("foo", replyTo, Encoding.UTF8.GetBytes("message")); Msg m = s.NextMessage(1000); Assert.NotNull(m); Assert.Equal(replyTo, m.Reply); byte[] reply = Encoding.UTF8.GetBytes("reply"); m.Respond(reply); m = r.NextMessage(1000); Assert.NotNull(m); Assert.Equal(replyTo, m.Subject); Assert.Equal(reply, m.Data); r.Unsubscribe(); } } } }
public void TestValidSubscriber() { using (NATSServer.CreateFastAndVerify(Context.Server1.Port)) { using (IConnection c = Context.OpenConnection(Context.Server1.Port)) { using (ISyncSubscription s = c.SubscribeSync("foo")) { Assert.True(s.IsValid); try { s.NextMessage(100); } catch (NATSTimeoutException) { } Assert.True(s.IsValid); s.Unsubscribe(); Assert.False(s.IsValid); try { s.NextMessage(100); } catch (NATSBadSubscriptionException) { } } } } }
public void TestSlowSubscriber() { Options opts = Context.GetTestOptions(Context.Server1.Port); opts.SubChannelLength = 10; using (NATSServer.CreateFastAndVerify(Context.Server1.Port)) { using (IConnection c = Context.ConnectionFactory.CreateConnection(opts)) { using (ISyncSubscription s = c.SubscribeSync("foo")) { Assert.ThrowsAny <Exception>(() => { for (int i = 0; i < (opts.SubChannelLength + 100); i++) { c.Publish("foo", null); } try { c.Flush(); } catch (Exception) { // ignore } s.NextMessage(); }); } } } }
public void TestRespondWithAutoUnsubscribe() { using (NATSServer.CreateFastAndVerify(Context.Server1.Port)) { using (IConnection c = Context.OpenConnection(Context.Server1.Port)) using (ISyncSubscription s = c.SubscribeSync("foo")) { s.AutoUnsubscribe(1); string replyTo = c.NewInbox(); using (ISyncSubscription r = c.SubscribeSync(replyTo)) { c.Publish("foo", replyTo, Encoding.UTF8.GetBytes("message")); Msg m = s.NextMessage(1000); Assert.NotNull(m); Assert.Equal(replyTo, m.Reply); byte[] reply = Encoding.UTF8.GetBytes("reply"); m.Respond(reply); m = r.NextMessage(1000); Assert.NotNull(m); Assert.Equal(replyTo, m.Subject); Assert.Equal(reply, m.Data); r.Unsubscribe(); } } } }
public void TestSyncSubscriptionPendingDrain() { int total = 100; byte[] data = Encoding.UTF8.GetBytes("0123456789"); using (NATSServer.CreateFastAndVerify(Context.Server1.Port)) { using (IConnection c = Context.OpenConnection(Context.Server1.Port)) { ISyncSubscription s = c.SubscribeSync("foo"); for (int i = 0; i < total; i++) { c.Publish("foo", data); } c.Flush(); while (s.Delivered != total) { s.NextMessage(100); } Assert.True(s.Dropped == 0); Assert.True(s.PendingBytes == 0); Assert.True(s.PendingMessages == 0); s.Unsubscribe(); } } }
public void TestClientAutoUnsub() { using (IConnection c = new ConnectionFactory().CreateConnection()) { 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.IsTrue(received == max); Assert.IsFalse(s.IsValid); } } }
private TimeSpan receiveSyncSubscriber(IConnection c, string subject) { Console.WriteLine("Start SyncSubscriber for {0}", subject); using (ISyncSubscription s = c.SubscribeSync(subject)) { Stopwatch sw = new Stopwatch(); while (received < options.Count) { if (received == 0) { sw.Start(); } Msg m = s.NextMessage(); received++; if (options.Verbose) { Console.WriteLine("Received: sub:{0} payload:{1}", m.Subject, Encoding.UTF8.GetString(m.Data)); } } sw.Stop(); return(sw.Elapsed); } }
private static void RequestResponseExplicit() { Console.Clear(); Console.WriteLine("Request/Response (explicit) demo"); Console.WriteLine("================================"); for (int i = 1; i <= _messageCount; i++) { string replySubject = $"_INBOX.{Guid.NewGuid().ToString("N")}"; ISyncSubscription subscription = _connection.SubscribeSync(replySubject); subscription.AutoUnsubscribe(1); // client also has a convenience-method to do this in line: //string replySubject = conn.NewInbox(); string message = $"Message {i}"; Console.WriteLine($"Sending: {message}"); // send with reply subject byte[] data = Encoding.UTF8.GetBytes(message); _connection.Publish("nats.demo.requestresponse", replySubject, data); // wait for response in reply subject var response = subscription.NextMessage(5000); string responseMsg = Encoding.UTF8.GetString(response.Data); Console.WriteLine($"Response: {responseMsg}"); Thread.Sleep(_sendIntervalMs); } }
public void TestTlsSuccessWithCert() { using (NATSServer srv = util.CreateServerWithConfig("tls_1222_verify.conf")) { Options opts = util.DefaultTestOptions; opts.Secure = true; opts.Url = "nats://localhost:1222"; opts.TLSRemoteCertificationValidationCallback = verifyServerCert; // .NET requires the private key and cert in the // same file. 'client.pfx' is generated from: // // openssl pkcs12 -export -out client.pfx // -inkey client-key.pem -in client-cert.pem X509Certificate2 cert = new X509Certificate2( UnitTestUtilities.GetFullCertificatePath("client.pfx"), "password"); opts.AddCertificate(cert); using (IConnection c = new ConnectionFactory().CreateConnection(opts)) { using (ISyncSubscription s = c.SubscribeSync("foo")) { c.Publish("foo", null); c.Flush(); Msg m = s.NextMessage(); } } } }
static void Main(string[] args) { Console.WriteLine("Starting consumer"); try { string url = $"nats://{args[0]}:{args[1]}"; Console.Title = $"Consumer - {url}"; var options = ConnectionFactory.GetDefaultOptions(); options.Url = url; options.NoEcho = true; options.Pedantic = false; options.Verbose = false; options.PingInterval = 10_000; options.AsyncErrorEventHandler += (sender, args) => { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] AsyncErrorEventHandler fired [ConnectionID={args.Conn.ConnectedId ?? "n/a"}; ConnectionURL={args.Conn.ConnectedUrl ?? "n/a"};]"); Console.WriteLine($" Error: {args.Error}"); }; options.ClosedEventHandler += (sender, args) => { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] ClosedEventHandler fired [ConnectionID={args.Conn.ConnectedId ?? "n/a"}; ConnectionURL={args.Conn.ConnectedUrl ?? "n/a"};]"); }; options.DisconnectedEventHandler += (sender, args) => { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] DisconnectedEventHandler fired [ConnectionID={args.Conn.ConnectedId ?? "n/a"}; ConnectionURL={args.Conn.ConnectedUrl ?? "n/a"};]"); }; options.ReconnectedEventHandler += (sender, args) => { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] ReconnectedEventHandler fired [ConnectionID={args.Conn.ConnectedId ?? "n/a"}; ConnectionURL={args.Conn.ConnectedUrl ?? "n/a"};]"); }; options.ServerDiscoveredEventHandler += (sender, args) => { Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] ServerDiscoveredEventHandler fired [ConnectionID={args.Conn.ConnectedId ?? "n/a"}; ConnectionURL={args.Conn.ConnectedUrl ?? "n/a"};]"); }; _connection = new ConnectionFactory().CreateConnection(options); _subscription = _connection.SubscribeSync("queue"); Console.WriteLine("Consuming"); while (_running) { var message = _subscription.NextMessage(); _connection.Publish(message.Reply, message.Data); _connection.Flush(); } } catch (Exception error) { Console.ForegroundColor = ConsoleColor.Red; Console.Write(error.ToString()); Console.ResetColor(); } }
public void TestClosedConnections() { using (NATSServer.CreateFastAndVerify(Context.Server1.Port)) { IConnection c = Context.OpenConnection(Context.Server1.Port); ISyncSubscription s = c.SubscribeSync("foo"); c.Close(); // While we can annotate all the exceptions in the test framework, // just do it manually. Assert.ThrowsAny <NATSConnectionClosedException>(() => c.Publish("foo", null)); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.Publish(new Msg("foo"))); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeAsync("foo")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeSync("foo")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeAsync("foo", "bar")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeSync("foo", "bar")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.Request("foo", null)); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.NextMessage()); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.NextMessage(100)); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.Unsubscribe()); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.AutoUnsubscribe(1)); } }
public void TestClosedConnections() { using (new NATSServer()) { IConnection c = utils.DefaultTestConnection; ISyncSubscription s = c.SubscribeSync("foo"); c.Close(); // While we can annotate all the exceptions in the test framework, // just do it manually. Assert.ThrowsAny <NATSConnectionClosedException>(() => c.Publish("foo", null)); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.Publish(new Msg("foo"))); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeAsync("foo")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeSync("foo")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeAsync("foo", "bar")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.SubscribeSync("foo", "bar")); Assert.ThrowsAny <NATSConnectionClosedException>(() => c.Request("foo", null)); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.NextMessage()); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.NextMessage(100)); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.Unsubscribe()); Assert.ThrowsAny <NATSConnectionClosedException>(() => s.AutoUnsubscribe(1)); } }
public void TestFlush() { using (var server = new NATSServer()) { var cf = new ConnectionFactory(); var opts = utils.DefaultTestOptions; opts.AllowReconnect = false; var c = cf.CreateConnection(opts); using (ISyncSubscription s = c.SubscribeSync("foo")) { c.Publish("foo", "reply", omsg); c.Flush(); } // Test a timeout, locally this may actually succeed, // so allow for that. // TODO: find a way to debug/pause the server to allow // for timeouts. try { c.Flush(1); } catch (NATSTimeoutException) {} Assert.Throws <ArgumentOutOfRangeException>(() => { c.Flush(-1); }); // test a closed connection c.Close(); Assert.Throws <NATSConnectionClosedException>(() => { c.Flush(); }); // test a lost connection c = cf.CreateConnection(opts); server.Shutdown(); Thread.Sleep(500); Assert.Throws <NATSConnectionClosedException>(() => { c.Flush(); }); } }
public void TestSlowSubscriber() { Options opts = utils.DefaultTestOptions; opts.SubChannelLength = 10; using (new NATSServer()) { using (IConnection c = new ConnectionFactory().CreateConnection(opts)) { using (ISyncSubscription s = c.SubscribeSync("foo")) { Assert.ThrowsAny <Exception>(() => { for (int i = 0; i < (opts.SubChannelLength + 100); i++) { c.Publish("foo", null); } try { c.Flush(); } catch (Exception) { // ignore } s.NextMessage(); }); } } } }
public void TestSyncSubscriptionPendingDrain() { 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(); while (s.Delivered != total) { s.NextMessage(100); } Assert.True(s.Dropped == 0); Assert.True(s.PendingBytes == 0); Assert.True(s.PendingMessages == 0); s.Unsubscribe(); } } }
public void TestSyncSubscriptionPendingDrain() { int total = 100; 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(); while (s.Delivered != total) { s.NextMessage(100); } Assert.IsTrue(s.Dropped == 0); Assert.IsTrue(s.PendingBytes == 0); Assert.IsTrue(s.PendingMessages == 0); s.Unsubscribe(); } }
public void TestValidSubscriber() { using (new NATSServer()) { using (IConnection c = utils.DefaultTestConnection) { using (ISyncSubscription s = c.SubscribeSync("foo")) { Assert.True(s.IsValid); try { s.NextMessage(100); } catch (NATSTimeoutException) { } Assert.True(s.IsValid); s.Unsubscribe(); Assert.False(s.IsValid); try { s.NextMessage(100); } catch (NATSBadSubscriptionException) { } } } } }
private void BtnHello_Click(object sender, EventArgs e) { if (c != null && !c.IsClosed()) { // Closing a connection c.Close(); TxtLog.Text += "\r\nDisconnected."; return; } TxtLog.Text = "Initialized"; // Create a new connection factory to create // a connection. ConnectionFactory cf = new ConnectionFactory(); c = cf.CreateConnection(); TxtLog.Text += "\r\nSending hello world"; ChannelMessage msg = new ChannelMessage(); msg.From = "csharp"; msg.Message = "Hello, World!"; msg.ChanNum = 5; c.Publish("world.channel_message", msg.ToByteArray()); // Simple synchronous subscriber sSync = c.SubscribeSync("world.channel_message"); TxtLog.Text += "\r\nWaiting for message..."; TmrMessage.Enabled = true; }
private TimeSpan receiveSyncSubscriber(IConnection c) { using (ISyncSubscription s = c.SubscribeSync(subject)) { Stopwatch sw = new Stopwatch(); while (received < count) { if (received == 0) { sw.Start(); } Msg m = s.NextMessage(); received++; if (verbose) { Console.WriteLine("Received: " + m); } } sw.Stop(); return(sw.Elapsed); } }
// ---------------------------------------------------------------------------------------------------- // READ MESSAGES // ---------------------------------------------------------------------------------------------------- public static IList <Msg> ReadMessagesAck(ISyncSubscription sub, bool verbose = true, int timeout = 1000) { if (verbose) { Console.Write("Read/Ack ->"); } IList <Msg> messages = new List <Msg>(); bool keepGoing = true; while (keepGoing) { try { Msg msg = sub.NextMessage(timeout); messages.Add(msg); msg.Ack(); if (verbose) { Console.Write(" " + msg.Subject + " / " + Encoding.UTF8.GetString(msg.Data)); } } catch (NATSTimeoutException) // timeout means there are no messages available { keepGoing = false; } } if (verbose) { Console.Write(messages.Count == 0 ? " No messages available <-\n" : " <-\n"); } return(messages); }
private TimeSpan receiveSyncSubscriber(IConnection c) { using (ISyncSubscription s = c.SubscribeSync(subject)) { s.NextMessage(); received++; Stopwatch sw = Stopwatch.StartNew(); while (received < count) { received++; Msg m = s.NextMessage(); if (verbose) { Console.WriteLine("Received: " + m); } replyMsg.Subject = m.Reply; c.Publish(replyMsg); } sw.Stop(); return(sw.Elapsed); } }
public void TestFlush() { using (IConnection c = new ConnectionFactory().CreateConnection()) { using (ISyncSubscription s = c.SubscribeSync("foo")) { c.Publish("foo", "reply", omsg); c.Flush(); } } }
public void TestClosedConnections() { IConnection c = new ConnectionFactory().CreateConnection(); ISyncSubscription s = c.SubscribeSync("foo"); c.Close(); // While we can annotate all the exceptions in the test framework, // just do it manually. UnitTestUtilities.testExpectedException( () => { c.Publish("foo", null); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { c.Publish(new Msg("foo")); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { c.SubscribeAsync("foo"); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { c.SubscribeSync("foo"); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { c.SubscribeAsync("foo", "bar"); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { c.SubscribeSync("foo", "bar"); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { c.Request("foo", null); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { s.NextMessage(); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { s.NextMessage(100); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { s.Unsubscribe(); }, typeof(NATSConnectionClosedException)); UnitTestUtilities.testExpectedException( () => { s.AutoUnsubscribe(1); }, typeof(NATSConnectionClosedException)); }
public void TestFlush() { using (new NATSServer()) { using (IConnection c = utils.DefaultTestConnection) { using (ISyncSubscription s = c.SubscribeSync("foo")) { c.Publish("foo", "reply", omsg); c.Flush(); } } } }
public void InitUsersAndGame(ISyncSubscription s, IConnection c, string subject) { Msg m; int init = 0; System.Threading.Thread.Sleep(1000); c.Publish(subject, subject + ".server", Encoding.UTF8.GetBytes("introduce")); while (init < 2) { m = s.NextMessage(); Console.WriteLine("recived init user: "******".server", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(State.Instance.CompressState()))); c.Flush(); m = s.NextMessage(); if (Encoding.UTF8.GetString(m.Data) == "initilised") { init++; } } }
public void TestQueueSubscriber() { using (IConnection c = new ConnectionFactory().CreateConnection()) { using (ISyncSubscription s1 = c.SubscribeSync("foo", "bar"), s2 = c.SubscribeSync("foo", "bar")) { c.Publish("foo", omsg); c.Flush(1000); if (s1.QueuedMessageCount + s2.QueuedMessageCount != 1) { Assert.Fail("Invalid message count in queue."); } // 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; if ((r1 + r2) != total) { Assert.Fail("Incorrect number of messages: {0} vs {1}", (r1 + r2), total); } if (Math.Abs(r1 - r2) > (total * .15)) { Assert.Fail("Too much variance between {0} and {1}", r1, r2); } } } }
public void TestPubWithReply() { using (IConnection c = new ConnectionFactory().CreateConnection()) { using (ISyncSubscription s = c.SubscribeSync("foo")) { c.Publish("foo", "reply", omsg); Msg m = s.NextMessage(1000); if (compare(omsg, m) == false) { Assert.Fail("Messages are not equal."); } } } }
public void TestDoubleUnsubscribe() { using (new NATSServer()) { using (IConnection c = utils.DefaultTestConnection) { using (ISyncSubscription s = c.SubscribeSync("foo")) { s.Unsubscribe(); Assert.ThrowsAny <Exception>(() => s.Unsubscribe()); } } } }
public void TestPubWithReply() { using (new NATSServer()) { using (IConnection c = utils.DefaultTestConnection) { using (ISyncSubscription s = c.SubscribeSync("foo")) { c.Publish("foo", "reply", omsg); Msg m = s.NextMessage(1000); Assert.True(compare(omsg, m), "Messages are not equal."); } } } }