static void Main(string[] args) { string brokerUrl = "amqp://localhost:5672"; string address = "my_queue"; Address brokerAddr = new Address(brokerUrl); Connection connection = new Connection(brokerAddr); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender", address); ReceiverLink receiver = new ReceiverLink(session, "receiver", address); Message helloOut = new Message("Hello World!"); sender.Send(helloOut); Message helloIn = receiver.Receive(); receiver.Accept(helloIn); Console.WriteLine(helloIn.Body.ToString()); receiver.Close(); sender.Close(); session.Close(); connection.Close(); }
public async Task WebSocketSendReceiveAsync() { string testName = "WebSocketSendReceiveAsync"; // assuming it matches the broker's setup and port is not taken Address wsAddress = new Address("ws://*****:*****@localhost:18080"); int nMsgs = 50; Connection connection = await Connection.Factory.CreateAsync(wsAddress); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; await sender.SendAsync(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); }
async Task RunSampleAsync() { ConnectionFactory factory = new ConnectionFactory(); factory.SASL.Profile = SaslProfile.External; Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Address address = new Address(this.Namespace, 5671, null, null, "/", "amqps"); var connection = await factory.CreateAsync(address); // before any operation can be performed, a token must be put to the $cbs node Trace.WriteLine(TraceLevel.Information, "Putting a token to the $cbs node..."); await PutTokenAsync(connection); Trace.WriteLine(TraceLevel.Information, "Sending a message..."); var session = new Session(connection); var sender = new SenderLink(session, "ServiceBus.Cbs:sender-link", this.Entity); await sender.SendAsync(new Message("test")); await sender.CloseAsync(); Trace.WriteLine(TraceLevel.Information, "Receiving the message back..."); var receiver = new ReceiverLink(session, "ServiceBus.Cbs:receiver-link", this.Entity); var message = await receiver.ReceiveAsync(); receiver.Accept(message); await receiver.CloseAsync(); Trace.WriteLine(TraceLevel.Information, "Closing the connection..."); await session.CloseAsync(); await connection.CloseAsync(); }
static void RunRequestClient(string address) { Connection connection = new Connection(new Address(address)); Session session = new Session(connection); string replyTo = "client-reply-to"; Attach recvAttach = new Attach() { Source = new Source() { Address = "request_processor" }, Target = new Target() { Address = replyTo } }; ReceiverLink receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null); SenderLink sender = new SenderLink(session, "request-client-sender", "request_processor"); Message request = new Message("hello"); request.Properties = new Properties() { MessageId = "request1", ReplyTo = replyTo }; sender.Send(request, null, null); Console.WriteLine("Sent request {0} body {1}", request.Properties, request.Body); Message response = receiver.Receive(); Console.WriteLine("Received response: {0} body {1}", response.Properties, response.Body); receiver.Accept(response); receiver.Close(); sender.Close(); session.Close(); connection.Close(); }
public void TestMethod_BasicSendReceive() { string testName = "BasicSendReceive"; const int nMsgs = 200; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message("msg" + i); message.Properties = new Properties() { GroupId = "abcdefg" }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
/// <summary> /// Creates the transport /// </summary> public AmqpLiteTransport(string inputQueueName) : base(inputQueueName) { amqpAddress = new AmqpLite.Address("rebustest.servicebus.windows.net", 5671, "rebustest", "SomeSecretKey"); amqpConnection = new AmqpLite.Connection(amqpAddress); amqpSession = new AmqpLite.Session(amqpConnection); if (inputQueueName != null) { amqpReceiver = new AmqpLite.ReceiverLink(amqpSession, "rebus-receiver", inputQueueName); } }
// // Sample invocation: Interop.Drain.exe --broker localhost:5672 --timeout 30 --address my-queue // static int Main(string[] args) { const int ERROR_SUCCESS = 0; const int ERROR_NO_MESSAGE = 1; const int ERROR_OTHER = 2; int exitCode = ERROR_SUCCESS; Connection connection = null; try { Options options = new Options(args); Address address = new Address(options.Url); connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-drain", options.Address); int timeout = int.MaxValue; if (!options.Forever) timeout = 1000 * options.Timeout; Message message = new Message(); int nReceived = 0; receiver.SetCredit(options.InitialCredit); while ((message = receiver.Receive(timeout)) != null) { nReceived++; if (!options.Quiet) { Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}", message.Properties, message.ApplicationProperties, message.Body); } receiver.Accept(message); if (options.Count > 0 && nReceived == options.Count) { break; } } if (message == null) { exitCode = ERROR_NO_MESSAGE; } receiver.Close(); session.Close(); connection.Close(); } catch (Exception e) { Console.WriteLine("Exception {0}.", e); if (null != connection) connection.Close(); exitCode = ERROR_OTHER; } return exitCode; }
protected void GetPartitions(Session session) { ReceiverLink receiverLink = null; SenderLink senderLink = null; try { // create a pair of links for request/response Trace.WriteLine(TraceLevel.Information, "Creating a request and a response link..."); string clientNode = "client-temp-node"; senderLink = new SenderLink(session, "mgmt-sender", "$management"); receiverLink = new ReceiverLink( session, "mgmt-receiver", new Attach() { Source = new Source() { Address = "$management" }, Target = new Target() { Address = clientNode } }, null); var request = new Amqp.Message(); request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode }; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "READ"; request.ApplicationProperties["name"] = settings.EventHubName; request.ApplicationProperties["type"] = "com.microsoft:eventhub"; senderLink.Send(request, null, null); var response = receiverLink.Receive(15000); // time out after 15 seconds if (response == null) { throw new Exception("No get partitions response was received."); } receiverLink.Accept(response); Trace.WriteLine(TraceLevel.Information, "Partition info {0}", response.Body.ToString()); var partitionStrings = (string[])((Map)response.Body)["partition_ids"]; Trace.WriteLine(TraceLevel.Information, "Partitions {0}", string.Join(",", partitionStrings)); this.partitions = new List<string>(partitionStrings); } catch (Exception x) { Trace.WriteLine(TraceLevel.Error, "Error retrieving partitions:\r\n{0}", x.ToString()); throw x; } finally { if (receiverLink != null) receiverLink.Close(); if (senderLink != null) senderLink.Close(); } }
static string[] GetPartitions() { Trace.WriteLine(TraceLevel.Information, "Retrieving partitions..."); Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Address address = new Address(sbNamespace, 5671, keyName, keyValue); Connection connection = new Connection(address); Trace.WriteLine(TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); // create a pair of links for request/response Trace.WriteLine(TraceLevel.Information, "Creating a request and a response link..."); string clientNode = "client-temp-node"; SenderLink sender = new SenderLink(session, "mgmt-sender", "$management"); ReceiverLink receiver = new ReceiverLink( session, "mgmt-receiver", new Attach() { Source = new Source() { Address = "$management" }, Target = new Target() { Address = clientNode } }, null); Message request = new Message(); request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode }; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "READ"; request.ApplicationProperties["name"] = entity; request.ApplicationProperties["type"] = "com.microsoft:eventhub"; sender.Send(request, null, null); Message response = receiver.Receive(); if (response == null) { throw new Exception("No response was received."); } receiver.Accept(response); receiver.Close(); sender.Close(); connection.Close(); Trace.WriteLine(TraceLevel.Information, "Partition info {0}", response.Body.ToString()); string[] partitions = (string[])((Map)response.Body)["partition_ids"]; Trace.WriteLine(TraceLevel.Information, "Partitions {0}", string.Join(",", partitions)); Trace.WriteLine(TraceLevel.Information, ""); return partitions; }
async Task PutTokenAsync(Connection connection) { var session = new Session(connection); string cbsClientAddress = "cbs-client-reply-to"; var cbsSender = new SenderLink(session, "cbs-sender", "$cbs"); var receiverAttach = new Attach() { Source = new Source() { Address = "$cbs" }, Target = new Target() { Address = cbsClientAddress } }; var cbsReceiver = new ReceiverLink(session, "cbs-receiver", receiverAttach, null); var sasToken = GetSASToken(this.KeyName, this.KeyValue, string.Format("http://{0}/{1}", this.Namespace, this.Entity), TimeSpan.FromMinutes(20)); Trace.WriteLine(TraceLevel.Information, " sas token: {0}", sasToken); // construct the put-token message var request = new Message(sasToken); request.Properties = new Properties(); request.Properties.MessageId = "1"; request.Properties.ReplyTo = cbsClientAddress; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "put-token"; request.ApplicationProperties["type"] = "servicebus.windows.net:sastoken"; request.ApplicationProperties["name"] = string.Format("amqp://{0}/{1}", this.Namespace, this.Entity); await cbsSender.SendAsync(request); Trace.WriteLine(TraceLevel.Information, " request: {0}", request.Properties); Trace.WriteLine(TraceLevel.Information, " request: {0}", request.ApplicationProperties); // receive the response var response = await cbsReceiver.ReceiveAsync(); if (response == null || response.Properties == null || response.ApplicationProperties == null) { throw new Exception("invalid response received"); } // validate message properties and status code. Trace.WriteLine(TraceLevel.Information, " response: {0}", response.Properties); Trace.WriteLine(TraceLevel.Information, " response: {0}", response.ApplicationProperties); int statusCode = (int)response.ApplicationProperties["status-code"]; if (statusCode != (int)HttpStatusCode.Accepted && statusCode != (int)HttpStatusCode.OK) { throw new Exception("put-token message was not accepted. Error code: " + statusCode); } // the sender/receiver may be kept open for refreshing tokens await cbsSender.CloseAsync(); await cbsReceiver.CloseAsync(); await session.CloseAsync(); }
public async Task<bool> ReceiveMessageFromDevice() { var receiver = new ReceiverLink(session, "receive-link", "/messages/servicebound/feedback"); while (true) { var message = await receiver.ReceiveAsync(); if (message == null) continue; receiver.Accept(message); return true; } }
private static Message ReceiveMessage(string queue) { var connection = new Connection(new Address("localhost", 5672, "user", "pass", "/", "AMQP")); var session = new Amqp.Session(connection); Amqp.Framing.Attach rcvAttach = new Amqp.Framing.Attach() { Source = new Amqp.Framing.Source() { Address = "/queue/" + queue, Durable = 1 }, Target = new Amqp.Framing.Target() { Durable = 1 } }; var receiver = new Amqp.ReceiverLink(session, "foo-receiver", rcvAttach, null); Amqp.Message amqpMessage = null; try { amqpMessage = receiver.Receive(new TimeSpan(0, 0, 5)); // wait - timeout 5 seconds if (amqpMessage == null) { // nothing received - timeout expired // queue is empty ! Console.WriteLine("No message received, queue is empty ..."); return(null); } else { receiver.Accept(amqpMessage); return(amqpMessage); } } catch (Exception ex) { throw ex; } }
static async Task<int> SslConnectionTestAsync(string brokerUrl, string address, string certfile) { try { ConnectionFactory factory = new ConnectionFactory(); factory.TCP.NoDelay = true; factory.TCP.SendBufferSize = 16 * 1024; factory.TCP.SendTimeout = 30000; factory.TCP.ReceiveBufferSize = 16 * 1024; factory.TCP.ReceiveTimeout = 30000; factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true; factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certfile)); factory.SSL.CheckCertificateRevocation = false; factory.AMQP.MaxFrameSize = 64 * 1024; factory.AMQP.HostName = "host.example.com"; factory.AMQP.ContainerId = "amq.topic"; Address sslAddress = new Address(brokerUrl); Connection connection = await factory.CreateAsync(sslAddress); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender1", address); ReceiverLink receiver = new ReceiverLink(session, "helloworld-receiver", address); Message helloOut = new Message("Hello - using client cert"); await sender.SendAsync(helloOut); Message helloIn = await receiver.ReceiveAsync(); receiver.Accept(helloIn); await connection.CloseAsync(); Console.WriteLine("{0}", helloIn.Body.ToString()); Console.WriteLine("Press enter key to exit..."); Console.ReadLine(); return 0; } catch (Exception e) { Console.WriteLine("Exception {0}.", e); return 1; } }
async Task SendReceiveAsync(int count) { Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Connection connection = await Connection.Factory.CreateAsync(this.GetAddress()); Trace.WriteLine(TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); Trace.WriteLine(TraceLevel.Information, "Creating a sender link..."); SenderLink sender = new SenderLink(session, "sessionful-sender-link", this.Entity); Trace.WriteLine(TraceLevel.Information, "Sending {0} messages...", count); for (int i = 0; i < count; i++) { Message message = new Message(); message.Properties = new Properties() { MessageId = "topic-test-" + i }; message.BodySection = new Data() { Binary = Encoding.UTF8.GetBytes("message #" + i) }; await sender.SendAsync(message); } Trace.WriteLine(TraceLevel.Information, "Closing sender..."); await sender.CloseAsync(); Trace.WriteLine(TraceLevel.Information, "Receiving messages from subscription..."); ReceiverLink receiver = new ReceiverLink(session, "receiver-link", this.Entity + "/Subscriptions/sub1"); for (int i = 0; i < count; i++) { Message message = await receiver.ReceiveAsync(30000); if (message == null) { break; } receiver.Accept(message); } Trace.WriteLine(TraceLevel.Information, "Closing receiver..."); await receiver.CloseAsync(); Trace.WriteLine(TraceLevel.Information, "Shutting down..."); await session.CloseAsync(); await connection.CloseAsync(); }
async static Task<bool> PutCbsToken(Connection connection, string host, string shareAccessSignature, string audience) { bool result = true; Session session = new Session(connection); string cbsReplyToAddress = "cbs-reply-to"; var cbsSender = new SenderLink(session, "cbs-sender", "$cbs"); var cbsReceiver = new ReceiverLink(session, cbsReplyToAddress, "$cbs"); // construct the put-token message var request = new Message(shareAccessSignature); request.Properties = new Properties(); request.Properties.MessageId = Guid.NewGuid().ToString(); request.Properties.ReplyTo = cbsReplyToAddress; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "put-token"; request.ApplicationProperties["type"] = "azure-devices.net:sastoken"; request.ApplicationProperties["name"] = audience; await cbsSender.SendAsync(request); // receive the response var response = await cbsReceiver.ReceiveAsync(); if (response == null || response.Properties == null || response.ApplicationProperties == null) { result = false; } else { int statusCode = (int)response.ApplicationProperties["status-code"]; string statusCodeDescription = (string)response.ApplicationProperties["status-description"]; if (statusCode != (int)202 && statusCode != (int)200) // !Accepted && !OK { result = false; } } // the sender/receiver may be kept open for refreshing tokens await cbsSender.CloseAsync(); await cbsReceiver.CloseAsync(); await session.CloseAsync(); return result; }
public void InitializeChannels(ReceiveLinkDescription[] receiveLinks) { InitializeConnectionAndSession(); foreach (var link in receiveLinks) { // Some sanity checks first if (link.Type != LinkType.Receive) continue; if (!this.partitions.Contains(link.PartitionId.ToString())) { throw new Exception(string.Format( "Partition '{0}' does not exist in this event hub and cannot be initialized.", link.PartitionId)); } string partitionAddress = string.Format( "{0}/ConsumerGroups/{1}/Partitions/{2}", this.settings.EventHubName, link.ConsumerGroup, link.PartitionId); var filters = BuildFilter(link); var amqpLink = new ReceiverLink( this.amqpSession, string.Format("receiver-{0}-{1}", this.Name, link.PartitionId), new Source() { Address = partitionAddress, FilterSet = filters }, null); this.channels.Add(link.Name, new ReceiveChannel() { Connection = amqpConnection, Session = amqpSession, Link = amqpLink, Name = link.Name, PartitionId = link.PartitionId.ToString() }); } }
static void ReceiveMessages(string node, int count, string sessionId) { Trace.WriteLine(TraceLevel.Information, "Establishing a connection..."); Address address = new Address(sbNamespace, 5671, keyName, keyValue); Connection connection = new Connection(address); Trace.WriteLine(TraceLevel.Information, "Creating a session..."); Session session = new Session(connection); Trace.WriteLine(TraceLevel.Information, "Accepting a message session '{0}'...", sessionId ?? "<any>"); Map filters = new Map(); filters.Add(new Symbol("com.microsoft:session-filter"), sessionId); ReceiverLink receiver = new ReceiverLink( session, "sessionful-receiver-link", new Source() { Address = node, FilterSet = filters }, null); for (int i = 0; i < count; i++) { Message message = receiver.Receive(30000); if (message == null) { break; } if (i == 0) { Trace.WriteLine(TraceLevel.Information, "Received message from session '{0}'", message.Properties.GroupId); } receiver.Accept(message); } Trace.WriteLine(TraceLevel.Information, "Finished receiving. Shutting down..."); Trace.WriteLine(TraceLevel.Information, ""); receiver.Close(); session.Close(); connection.Close(); }
static async Task Run() { string address = "amqp://*****:*****@localhost:5672"; Connection connection = await Connection.Factory.CreateAsync(new Address(address)); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "test-sender", "q1"); Message message1 = new Message("Hello AMQP!"); await sender.SendAsync(message1); ReceiverLink receiver = new ReceiverLink(session, "test-receiver", "q1"); Message message2 = await receiver.ReceiveAsync(); Console.WriteLine(message2.GetBody<string>()); receiver.Accept(message2); await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); }
/// <summary> /// Receives a message asynchronously. /// </summary> /// <param name="receiver">The link.</param> /// <param name="timeout">The timeout in seconds.</param> /// <returns></returns> public static Task <Message> ReceiveAsync(this ReceiverLink receiver, int timeout = 60000) { TaskCompletionSource <Message> tcs = new TaskCompletionSource <Message>(); try { var message = receiver.ReceiveInternal( (l, m) => tcs.SetResult(m), timeout); if (message != null) { tcs.SetResult(message); } } catch (Exception exception) { tcs.SetException(exception); } return(tcs.Task); }
string[] GetPartitions() { Address address = new Address(sbNamespace, 5671, ReckeyName, ReckeyValue); Connection connection = new Connection(address); Session session = new Session(connection); // create a pair of links for request/response string clientNode = "client-temp-node"; SenderLink sender = new SenderLink(session, "mgmt-sender", "$management"); ReceiverLink receiver = new ReceiverLink( session, "mgmt-receiver", new Attach() { Source = new Source() { Address = "$management" }, Target = new Target() { Address = clientNode } }, null); Message request = new Message(); request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode }; request.ApplicationProperties = new ApplicationProperties(); request.ApplicationProperties["operation"] = "READ"; request.ApplicationProperties["name"] = entity; request.ApplicationProperties["type"] = "com.microsoft:eventhub"; sender.Send(request, null, null); Message response = receiver.Receive(); if (response == null) { throw new Exception("No response was received."); } receiver.Accept(response); receiver.Close(); sender.Close(); connection.Close(); string[] partitions = (string[])((Map)response.Body)["partition_ids"]; return partitions; }
/// <summary> /// Receives a message asynchronously. /// </summary> /// <param name="receiver">The receiver link.</param> /// <param name="timeout">The timeout in milliseconds to wait for a message.</param> /// <returns>A Task for the asynchronous receive operation. The result is a Message object /// if available; otherwise a null value.</returns> public static Task <Message> ReceiveAsync(this ReceiverLink receiver, int timeout = 60000) { TaskCompletionSource <Message> tcs = new TaskCompletionSource <Message>(); var message = receiver.ReceiveInternal( (l, m) => { if (l.Error != null) { tcs.TrySetException(new AmqpException(l.Error)); } else { tcs.TrySetResult(m); } }, timeout); if (message != null) { tcs.TrySetResult(message); } return(tcs.Task); }
public void ContainerHostRequestProcessorTest() { string name = MethodInfo.GetCurrentMethod().Name; var processor = new TestRequestProcessor(); this.host.RegisterRequestProcessor(name, processor); int count = 500; var connection = new Connection(Address); var session = new Session(connection); string replyTo = "client-reply-to"; Attach recvAttach = new Attach() { Source = new Source() { Address = name }, Target = new Target() { Address = replyTo } }; var doneEvent = new ManualResetEvent(false); List<string> responses = new List<string>(); ReceiverLink receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null); receiver.Start( 20, (link, message) => { responses.Add(message.GetBody<string>()); link.Accept(message); if (responses.Count == count) { doneEvent.Set(); } }); SenderLink sender = new SenderLink(session, "request-client-sender", name); for (int i = 0; i < count; i++) { Message request = new Message("Hello"); request.Properties = new Properties() { MessageId = "request" + i, ReplyTo = replyTo }; sender.Send(request, SendTimeout); } Assert.IsTrue(doneEvent.WaitOne(10000), "Not completed in time"); receiver.Close(); sender.Close(); session.Close(); connection.Close(); Assert.AreEqual(count, processor.TotalCount); Assert.AreEqual(count, responses.Count); for (int i = 1; i <= count; i++) { Assert.AreEqual("OK" + i, responses[i - 1]); } }
int state; // 0: created, 1: waiting, 2: signaled public AsyncWaiter(ReceiverLink link, MessageCallback callback) { this.link = link; this.callback = callback; }
public void TestMethod_LinkReopen() { string testName = "LinkReopen"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender", testTarget.Path); sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } }); sender.Close(); sender = new SenderLink(session, "sender", testTarget.Path); sender.Send(new Message("test2") { Properties = new Properties() { MessageId = testName } }); sender.Close(); ReceiverLink receiver = new ReceiverLink(session, "receiver", testTarget.Path); for (int i = 1; i <= 2; i++) { var m = receiver.Receive(); Assert.IsTrue(m != null, "Didn't receive message " + i); receiver.Accept(m); } session.Close(0); connection.Close(); Assert.IsTrue(connection.Error == null, "connection has error!"); }
public void TestMethod_ConnectionFrameSize() { string testName = "ConnectionFrameSize"; const int nMsgs = 200; int frameSize = 4 * 1024; Connection connection = new Connection(testTarget.Address, null, new Open() { ContainerId = "c1", MaxFrameSize = (uint)frameSize }, null); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(new string('A', frameSize + (i - nMsgs / 2))); sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = receiver.Receive(); string value = (string)message.Body; Trace.WriteLine(TraceLevel.Verbose, "receive: {0}x{1}", value[0], value.Length); receiver.Accept(message); } sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_AdvancedLinkFlowControl() { string testName = "AdvancedLinkFlowControl"; int nMsgs = 20; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i }; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); receiver.SetCredit(2, false); Message m1 = receiver.Receive(); Message m2 = receiver.Receive(); Assert.AreEqual("msg0", m1.Properties.MessageId); Assert.AreEqual("msg1", m2.Properties.MessageId); receiver.Accept(m1); receiver.Accept(m2); ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path); receiver2.SetCredit(2, false); Message m3 = receiver2.Receive(); Message m4 = receiver2.Receive(); Assert.AreEqual("msg2", m3.Properties.MessageId); Assert.AreEqual("msg3", m4.Properties.MessageId); receiver2.Accept(m3); receiver2.Accept(m4); receiver.SetCredit(4); for (int i = 4; i < nMsgs; i++) { Message m = receiver.Receive(); Assert.AreEqual("msg" + i, m.Properties.MessageId); receiver.Accept(m); } sender.Close(); receiver.Close(); receiver2.Close(); session.Close(); connection.Close(); }
public void TestMethod_LinkCreateClose() { Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender", testTarget.Path); ReceiverLink receiver = new ReceiverLink(session, "receiver", testTarget.Path); sender.Close(0); receiver.Close(0); session.Close(0); connection.Close(); Assert.IsTrue(connection.Error == null, "connection has error!"); }
public void TestMethod_DynamicReceiverLink() { string testName = "DynamicReceiverLink"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); string remoteSource = null; ManualResetEvent attached = new ManualResetEvent(false); OnAttached onAttached = (link, attach) => { remoteSource = ((Source)attach.Source).Address; attached.Set(); }; ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Dynamic = true }, onAttached); attached.WaitOne(10000); Assert.IsTrue(remoteSource != null, "dynamic source not attached"); SenderLink sender = new SenderLink(session, "sender-" + testName, remoteSource); Message message = new Message("hello"); sender.Send(message, 60000); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_RequestResponse() { string testName = "RequestResponse"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); // server app: the request handler ReceiverLink requestLink = new ReceiverLink(session, "srv.requester-" + testName, testTarget.Path); requestLink.Start(10, (l, m) => { l.Accept(m); // got a request, send back a reply SenderLink sender = new SenderLink(session, "srv.replier-" + testName, m.Properties.ReplyTo); Message reply = new Message("received"); reply.Properties = new Properties() { CorrelationId = m.Properties.MessageId }; sender.Send(reply, (a, b, c) => ((Link)c).Close(0), sender); }); // client: setup a temp queue and waits for responses OnAttached onAttached = (l, at) => { // client: sends a request to the request queue, specifies the temp queue as the reply queue SenderLink sender = new SenderLink(session, "cli.requester-" + testName, testTarget.Path); Message request = new Message("hello"); request.Properties = new Properties() { MessageId = "request1", ReplyTo = ((Source)at.Source).Address }; sender.Send(request, (a, b, c) => ((Link)c).Close(0), sender); }; ReceiverLink responseLink = new ReceiverLink(session, "cli.responder-" + testName, new Source() { Dynamic = true }, onAttached); Message response = responseLink.Receive(); Assert.IsTrue(response != null, "no response was received"); responseLink.Accept(response); requestLink.Close(); responseLink.Close(); session.Close(); connection.Close(); }
public void TestMethod_SynchronousSend() { string testName = "SynchronousSend"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); Message message = new Message("hello"); sender.Send(message, 60000); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_DynamicSenderLink() { string testName = "DynamicSenderLink"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); string targetAddress = null; OnAttached onAttached = (link, attach) => { targetAddress = ((Target)attach.Target).Address; }; SenderLink sender = new SenderLink(session, "sender-" + testName, new Target() { Dynamic = true }, onAttached); Message message = new Message("hello"); sender.Send(message, 60000); Assert.IsTrue(targetAddress != null, "dynamic target not attached"); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, targetAddress); message = receiver.Receive(); Assert.IsTrue(message != null, "no message was received."); receiver.Accept(message); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_ReceiveWithFilter() { string testName = "ReceiveWithFilter"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); Message message = new Message("I can match a filter"); message.Properties = new Properties() { GroupId = "abcdefg" }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = 100; SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); sender.Send(message, null, null); // update the filter descriptor and expression according to the broker Map filters = new Map(); // JMS selector filter: code = 0x0000468C00000004L, symbol="apache.org:selector-filter:string" filters.Add(new Symbol("f1"), new DescribedValue(new Symbol("apache.org:selector-filter:string"), "sn = 100")); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Address = testTarget.Path, FilterSet = filters }, null); Message message2 = receiver.Receive(); receiver.Accept(message2); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
/// <summary> /// Receives a message asynchronously. /// </summary> /// <param name="receiver">The receiver link.</param> /// <param name="timeout">The timeout to wait for a message.</param> /// <returns>A Task for the asynchronous receive operation. The result is a Message object /// if available; otherwise a null value.</returns> public static Task <Message> ReceiveAsync(this ReceiverLink receiver, TimeSpan timeout) { return(ReceiveAsync(receiver, (int)timeout.TotalMilliseconds)); }
public void TestMethod_ReceiveWaiter() { string testName = "ReceiveWaiter"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); ManualResetEvent gotMessage = new ManualResetEvent(false); Fx.StartThread(() => { Message message = receiver.Receive(); if (message != null) { Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); gotMessage.Set(); } }); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); Message msg = new Message() { Properties = new Properties() { MessageId = "123456" } }; sender.Send(msg, null, null); Assert.IsTrue(gotMessage.WaitOne(5000), "No message was received"); sender.Close(); receiver.Close(); session.Close(); connection.Close(); }
public void TestMethod_MessageId() { string testName = "MessageId"; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); object[] idList = new object[] { null, "string-id", 20000UL, Guid.NewGuid(), Encoding.UTF8.GetBytes("binary-id") }; SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < idList.Length; ++i) { Message message = new Message() { Properties = new Properties() }; message.Properties.SetMessageId(idList[i]); message.Properties.SetCorrelationId(idList[(i + 2) % idList.Length]); sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < idList.Length; ++i) { Message message = receiver.Receive(); receiver.Accept(message); Assert.AreEqual(idList[i], message.Properties.GetMessageId()); Assert.AreEqual(idList[(i + 2) % idList.Length], message.Properties.GetCorrelationId()); } connection.Close(); // invalid types Properties prop = new Properties(); try { prop.SetMessageId(0); Assert.IsTrue(false, "not a valid identifier type"); } catch (AmqpException ae) { Assert.AreEqual(ErrorCode.NotAllowed, (string)ae.Error.Condition); } try { prop.SetCorrelationId(new Symbol("symbol")); Assert.IsTrue(false, "not a valid identifier type"); } catch (AmqpException ae) { Assert.AreEqual(ErrorCode.NotAllowed, (string)ae.Error.Condition); } }
public async Task BasicSendReceiveAsync() { string testName = "BasicSendReceiveAsync"; int nMsgs = 100; Connection connection = await Connection.Factory.CreateAsync(this.testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; message.ApplicationProperties = new ApplicationProperties(); message.ApplicationProperties["sn"] = i; await sender.SendAsync(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; ++i) { Message message = await receiver.ReceiveAsync(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]); receiver.Accept(message); } await sender.CloseAsync(); await receiver.CloseAsync(); await session.CloseAsync(); await connection.CloseAsync(); }