Defines the address of an AMQP endpoint. An address has the following form: amqp[s] :// [user:[password]@] domain[:port] [/[path] Where domain can be: host | ip | name If "amqps" is specified, the connection uses TLS in the underlying transport. When port is not specified, it is set to the standard based on scheme (amqp: 5672, amqps: 5671) path is not used by the library. Note that TLS Server Name Indication (SNI) is signaled only for "amqps" addresses where the domain is host | name. SNI is not signaled when the domain is a numeric IP address.
        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();
        }
示例#2
0
        static void Main(string[] args)
        {
            Amqp.Trace.TraceLevel = Amqp.TraceLevel.Frame | Amqp.TraceLevel.Verbose;
            #if NETMF
            Amqp.Trace.TraceListener = (f, a) => Debug.Print(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));
            #else
            Amqp.Trace.TraceListener = (f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));
            #endif
            address = new Address(HOST, PORT, null, null);
            connection = new Connection(address);

            string audience = Fx.Format("{0}/devices/{1}", HOST, DEVICE_ID);
            string resourceUri = Fx.Format("{0}/devices/{1}", HOST, DEVICE_ID);

            string sasToken = GetSharedAccessSignature(null, DEVICE_KEY, resourceUri, new TimeSpan(1, 0, 0));
            bool cbs = PutCbsToken(connection, HOST, sasToken, audience);

            if (cbs)
            {
                session = new Session(connection);

                SendEvent();
                receiverThread = new Thread(ReceiveCommands);
                receiverThread.Start();
            }

            // just as example ...
            // the application ends only after received a command or timeout on receiving
            receiverThread.Join();

            session.Close();
            connection.Close();
        }
        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();
        }
        /// <summary>
        /// Creates a new connection with a custom open frame and a callback to handle remote open frame.
        /// </summary>
        /// <param name="address">The address of remote endpoint to connect to.</param>
        /// <param name="open">If specified, it is sent to open the connection, otherwise an open frame created from the AMQP settings property is sent.</param>
        /// <param name="onOpened">If specified, it is invoked when an open frame is received from the remote peer.</param>
        /// <returns></returns>
        public async Task<Connection> CreateAsync(Address address, Open open, OnOpened onOpened)
        {
            IAsyncTransport transport;
            if (WebSocketTransport.MatchScheme(address.Scheme))
            {
                WebSocketTransport wsTransport = new WebSocketTransport();
                await wsTransport.ConnectAsync(address);
                transport = wsTransport;
            }
            else
            {
                TcpTransport tcpTransport = new TcpTransport();
                await tcpTransport.ConnectAsync(address, this);
                transport = tcpTransport;
            }

            if (address.User != null)
            {
                SaslPlainProfile profile = new SaslPlainProfile(address.User, address.Password);
                transport = await profile.OpenAsync(address.Host, transport);
            }
            else if (this.saslSettings != null && this.saslSettings.Profile != null)
            {
                transport = await this.saslSettings.Profile.OpenAsync(address.Host, transport);
            }

            AsyncPump pump = new AsyncPump(transport);
            Connection connection = new Connection(this.AMQP, address, transport, open, onOpened);
            pump.Start(connection);

            return connection;
        }
示例#5
0
        internal async Task<IAsyncTransport> ConnectAsync(Address address, Action<ClientWebSocketOptions> options)
        {
            Uri uri = new UriBuilder()
            {
                Scheme = address.Scheme,
                Port = GetDefaultPort(address.Scheme, address.Port),
                Host = address.Host,
                Path = address.Path
            }.Uri;

            ClientWebSocket cws = new ClientWebSocket();
            cws.Options.AddSubProtocol(WebSocketSubProtocol);
            if (options != null)
            {
                options(cws.Options);
            }

            await cws.ConnectAsync(uri, CancellationToken.None);
            if (cws.SubProtocol != WebSocketSubProtocol)
            {
                cws.Abort();

                throw new NotSupportedException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "WebSocket SubProtocol used by the host is not the same that was requested: {0}",
                        cws.SubProtocol ?? "<null>"));
            }

            this.webSocket = cws;

            return this;
        }
示例#6
0
        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();
        }
示例#7
0
        public static void Main()
        {
            // write your code here

            // wait for DHCP-allocated IP address
            // while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) ;

            // wait for network connectivity
            // while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) ;

            Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
            Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;

            networkAvailableEvent.WaitOne();
            Debug.Print("link is up!");
            networkAddressChangedEvent.WaitOne();
            Debug.Print("address acquired: " + Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress);

            Debug.Print("\r\n*** GET NETWORK INTERFACE SETTINGS ***");
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface[] networkInterfaces = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            Debug.Print("Found " + networkInterfaces.Length + " network interfaces.");

            // get date/time via NTP
            DateTime dateTime = MFToolkit.Net.Ntp.NtpClient.GetNetworkTime();
            Utility.SetLocalTime(dateTime);

            Amqp.Trace.TraceLevel = Amqp.TraceLevel.Frame | Amqp.TraceLevel.Verbose;
            #if NETMF
            Amqp.Trace.TraceListener = (f, a) => Debug.Print(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));
            #else
            Amqp.Trace.TraceListener = (f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));
            #endif
            address = new Address(HOST, PORT, null, null);
            connection = new Connection(address);

            string audience = Fx.Format("/devices/{0}/events", DEVICE_ID);
            string resourceUri = Fx.Format("{0}/devices/{1}", HOST, DEVICE_ID);

            string sasToken = GetSharedAccessSignature(null, DEVICE_KEY, resourceUri, new TimeSpan(1, 0, 0));
            bool cbs = PutCbsToken(connection, HOST, sasToken, audience);

            if (cbs)
            {
                session = new Session(connection);

                SendEvent();
                receiverThread = new Thread(ReceiveCommands);
                receiverThread.Start();
            }

            // just as example ...
            // the application ends only after received a command or timeout on receiving
            receiverThread.Join();

            session.Close();
            connection.Close();

            Thread.Sleep(Timeout.Infinite);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="baseAddress">Base address to service bus</param>
        /// <param name="settings">AMQP transport settings</param>
        public AmqpMessagingFactory(Uri baseAddress, AmqpTransportSettings settings)
        {
            this.Address = baseAddress;
            this.settings = settings;

            SharedAccessSignatureTokenProvider sasTokenProvider = (SharedAccessSignatureTokenProvider)this.ServiceBusSecuritySettings.TokenProvider;
            this.amqpAddress = new Address(this.Address.Host, this.TransportSettings.Port, sasTokenProvider.KeyName, sasTokenProvider.SharedAccessKey);
        }
示例#9
0
        public AmqpConnectorsTest(AmqpFixture fixture, ITestOutputHelper output) :
            base((ActorSystem)null, output)
        {
            _materializer = ActorMaterializer.Create(Sys);
            _serializer   = Sys.Serialization.FindSerializerForType(typeof(string));
            _fixture      = fixture;

            _address = new Address(_fixture.HostName, _fixture.AmqpPort, _fixture.UserName, _fixture.Password, scheme: "AMQP");
        }
示例#10
0
 public void Connect(Connection connection, Address address, bool noVerification)
 {
     this.connection = connection;
     this.socket = new StreamSocket();
     this.socket.ConnectAsync(
         new HostName(address.Host),
         address.Port.ToString(),
         address.UseSsl ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket).AsTask().GetAwaiter().GetResult();
 }
示例#11
0
        public async Task ConnectAsync(Address address, ConnectionFactory factory)
        {
            StreamSocket ss = new StreamSocket();
            await ss.ConnectAsync(
                new HostName(address.Host),
                address.Port.ToString(),
                address.UseSsl ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket);

            this.socket = ss;
        }
示例#12
0
            public override Task<IAsyncTransport> CreateAsync(Address address)
            {
                NamedPipeClientStream client = new NamedPipeClientStream(address.Host, address.Path,
                    PipeDirection.InOut, PipeOptions.Asynchronous);
                client.Connect();

                TaskCompletionSource<IAsyncTransport> tcs = new TaskCompletionSource<IAsyncTransport>();
                tcs.SetResult(new NamedPipeTransport(client));
                return tcs.Task;
            }
示例#13
0
        //
        // Sample invocation: Interop.Spout.exe --broker localhost:5672 --timeout 30 --address my-queue
        //
        static int Main(string[] args)
        {
            const int ERROR_SUCCESS = 0;
            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);
                SenderLink sender = new SenderLink(session, "sender-spout", options.Address);
                // TODO: ReplyTo

                Stopwatch stopwatch = new Stopwatch();
                TimeSpan timespan = new TimeSpan(0, 0, options.Timeout);
                stopwatch.Start();
                for (int nSent = 0;
                    (0 == options.Count || nSent < options.Count) &&
                    (0 == options.Timeout || stopwatch.Elapsed <= timespan);
                    nSent++)
                {
                    string id = options.Id;
                    if (id.Equals(""))
                    {
                        Guid g = Guid.NewGuid();
                        id = g.ToString();
                    }
                    id += ":" + nSent.ToString();

                    Message message = new Message(options.Content);
                    message.Properties = new Properties() { MessageId = id };
                    sender.Send(message);
                    if (options.Print)
                    {
                        Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}",
                                      message.Properties, message.ApplicationProperties, message.Body);
                    }
                }
                sender.Close();
                session.Close();
                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                if (null != connection)
                    connection.Close();
                exitCode = ERROR_OTHER;
            }
            return exitCode;
        }
示例#14
0
        /// <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);
            }
        }
示例#15
0
        void Connect()
        {
            _address = new Amqp.Address(
                string.Format("{0}.servicebus.windows.net", _servicebusNamespace),
                5671, _saPolicyName, _saKey);

            _connection = new Amqp.Connection(_address);
            _session    = new Amqp.Session(_connection);
            _senderlink = new Amqp.SenderLink(_session,
                                              string.Format("send-link:{0}", _saPolicyName), _eventHubName);
        }
示例#16
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            this.connection = connection;
            var factory = new ConnectionFactory();
            if (noVerification)
            {
                factory.SSL.RemoteCertificateValidationCallback = noneCertValidator;
            }

            this.ConnectAsync(address, factory).GetAwaiter().GetResult();
        }
示例#17
0
        public async Task ConnectAsync(Address address, ConnectionFactory factory)
        {
            Socket socket;
            IPAddress[] ipAddresses;
            IPAddress ipAddress;
            if (IPAddress.TryParse(address.Host, out ipAddress))
            {
                socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                ipAddresses = new IPAddress[] { ipAddress };
            }
            else
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ipAddresses = Dns.GetHostEntry(address.Host).AddressList;
            }

            if (factory.tcpSettings != null)
            {
                factory.tcpSettings.Configure(socket);
            }

            await Task.Factory.FromAsync(
                (c, s) => ((Socket)s).BeginConnect(ipAddresses, address.Port, c, s),
                (r) => ((Socket)r.AsyncState).EndConnect(r),
                socket);

            IAsyncTransport transport;
            if (address.UseSsl)
            {
                SslStream sslStream;
                var ssl = factory.SslInternal;
                if (ssl == null)
                {
                    sslStream = new SslStream(new NetworkStream(socket));
                    await sslStream.AuthenticateAsClientAsync(address.Host);
                }
                else
                {
                    sslStream = new SslStream(new NetworkStream(socket), false, ssl.RemoteCertificateValidationCallback);
                    await sslStream.AuthenticateAsClientAsync(address.Host, ssl.ClientCertificates,
                        ssl.Protocols, ssl.CheckCertificateRevocation);
                }

                transport = new SslSocket(this, sslStream);
            }
            else
            {
                transport = new TcpSocket(this, socket);
            }

            this.socketTransport = transport;
            this.writer = new Writer(this, this.socketTransport);
        }
示例#18
0
        public MainPage()
        {
            this.InitializeComponent();

            Amqp.Trace.TraceLevel = Amqp.TraceLevel.Frame | Amqp.TraceLevel.Verbose;
            Amqp.Trace.TraceListener = (f, a) => System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));

            address = new Address(HOST, PORT, null, null);
            connection = new Connection(address);

            session = new Session(connection);
        }
示例#19
0
        //
        // 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;
        }
示例#20
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            var ipHostEntry = Dns.GetHostEntry(address.Host);
            Exception exception = null;
            TcpSocket socket = null;

            foreach (var ipAddress in ipHostEntry.AddressList)
            {
                if (ipAddress == null)
                {
                    continue;
                }

                try
                {
                    socket = new TcpSocket();
                    socket.Connect(new IPEndPoint(ipAddress, address.Port));
                    exception = null;
                    break;
                }
                catch (SocketException socketException)
                {
                    if (socket != null)
                    {
                        socket.Close();
                        socket = null;
                    }

                    exception = socketException;
                }
            }

            if (exception != null)
            {
                throw exception;
            }

            if (address.UseSsl)
            {
                SslSocket sslSocket = new SslSocket(socket);
                sslSocket.AuthenticateAsClient(
                    address.Host,
                    null,
                    noVerification ? SslVerification.NoVerification : SslVerification.VerifyPeer,
                    SslProtocols.Default);
                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }
示例#21
0
        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;
        }
示例#22
0
        public SenderLink GetMessageSender(string topic)
        {
            if (_senders.ContainsKey(topic))
                return _senders[topic];

            Address address = new Address("amqp://*****:*****@localhost:5672");
            Connection connection = Connection.Factory.CreateAsync(address).Result;
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender", topic);

            _senders.TryAdd(topic, sender);
            sender.Closed += Sender_Closed;
            return sender;
        }
示例#23
0
        public async Task ConnectAsync(Address address, ConnectionFactory factory)
        {
            SocketProtectionLevel spl = !address.UseSsl ?
                SocketProtectionLevel.PlainSocket :
#if NETFX_CORE
                SocketProtectionLevel.Tls12;
#else
                SocketProtectionLevel.Ssl;
#endif
            StreamSocket ss = new StreamSocket();
            await ss.ConnectAsync(new HostName(address.Host), address.Port.ToString(), spl);

            this.socket = ss;
        }
示例#24
0
        public TestTarget()
        {
#if !COMPACT_FRAMEWORK && !NETFX_CORE && !NETMF
            this.address = Environment.GetEnvironmentVariable(envVarName);
#endif
            if (this.address == null)
            {
                this.address = defaultAddress;
            }

            // Verify that the URI is well formed.
            Address addr = new Address(this.address);
            // Extract the path without the leading "/".
            path = addr.Path.Substring(1);
        }
示例#25
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            TcpSocket socket = new TcpSocket();
            socket.Connect(address.Host, address.Port);

            if (address.UseSsl)
            {
                SslSocket sslSocket = new SslSocket(socket, noVerification);
                sslSocket.AuthenticateAsClient(address.Host);
                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }
示例#26
0
    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;
      }
    }
示例#27
0
 public AmqpTransportReceiver(AmqpMessageReceiverConfiguration config, AmqpServiceBusConfiguration serviceBusConfig)
 {
     amqpAddress = serviceBusConfig.AmqpAddress;
     ReceiverLinkAddress = config.ReceiverLinkAddress;
     MaxRetries = config.MaxRetries;
     if (MaxRetries < 0)
     {
         MaxRetries = 0;
     }
     MaxConcurrency = config.MaxConcurrency;
     if (MaxConcurrency < 0)
     {
         MaxConcurrency = 0;
     }
     messageMapper = serviceBusConfig.MessageMapper;
     messageEncoder = serviceBusConfig.MessageEncoder;
     faultManager = new TransportMessageFaultManager(MaxRetries);
 }
示例#28
0
        public async Task ConnectAsync(Address address)
        {
            StreamWebSocket sws = new StreamWebSocket();
            sws.Control.SupportedProtocols.Add(WebSocketSubProtocol);
            sws.Closed += this.OnWebSocketClosed;

            Uri uri = new UriBuilder()
            {
                Scheme = address.Scheme,
                Port = GetDefaultPort(address.Scheme, address.Port),
                Host = address.Host,
                Path = address.Path
            }.Uri;

            await sws.ConnectAsync(uri);

            this.webSocket = sws;
        }
示例#29
0
        public async Task TestHelloWorld()
        {
            Connection.DisableServerCertValidation = true;
            Trace.TraceLevel    = TraceLevel.Frame;
            Trace.TraceListener = (l, f, a) =>
                                  _output.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            //strange, works using regular activeMQ and the amqp test broker from here: http://azure.github.io/amqpnetlite/articles/hello_amqp.html
            //but this does not work in ActiveMQ Artemis
            var address    = new Address(_fixture.HostName, _fixture.AmqpPort, _fixture.UserName, _fixture.Password, scheme: "AMQP");
            var connection = new Connection(address);
            var session    = new Session(connection);

            var message = new Message("Hello AMQP");

            var target = new Target
            {
                Address      = "q1",
                Capabilities = new Symbol[] { new Symbol("queue") }
            };

            var sender = new SenderLink(session, "sender-link", target, null);
            await sender.SendAsync(message);

            var source = new Source
            {
                Address      = "q1",
                Capabilities = new Symbol[] { new Symbol("queue") }
            };

            var receiver = new ReceiverLink(session, "receiver-link", source, null);

            message = await receiver.ReceiveAsync();

            receiver.Accept(message);

            await sender.CloseAsync();

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();
        }
示例#30
0
        // This functionis used to query the Management data
        private Message QueryManagementData()
        {
            Address address = new Address(sbNamespace, PORT, keyName, keyValue);
            Connection connection = new Connection(address);

            Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a session...");
            Session session = new Session(connection);

            // create a pair of links for request/response
            Trace.WriteLine(Amqp.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();
            return response;
        }
示例#31
0
        public async Task WebSocketSendReceiveAsync()
        {
            if (Environment.GetEnvironmentVariable("CoreBroker") == "1")
            {
                // No Websocket listener on .Net Core
                return;
            }

            string testName = "WebSocketSendReceiveAsync";

            // assuming it matches the broker's setup and port is not taken
            Address wsAddress = new Address(address);
            int nMsgs = 50;

            ConnectionFactory connectionFactory = new ConnectionFactory(
                new TransportProvider[] { new WebSocketTransportFactory() });
            Connection connection = await connectionFactory.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();
        }
示例#32
0
        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();
        }
示例#33
0
        public async Task ConnectAsync(Address address, ConnectionFactory factory)
        {
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

            if (factory.tcpSettings != null)
            {
                factory.tcpSettings.Configure(socket);
            }

            await Task.Factory.FromAsync(
                (c, s) => ((Socket)s).BeginConnect(address.Host, address.Port, c, s),
                (r) => ((Socket)r.AsyncState).EndConnect(r),
                socket);

            IAsyncTransport transport;
            if (address.UseSsl)
            {
                SslStream sslStream;
                var ssl = factory.SslInternal;
                if (ssl == null)
                {
                    sslStream = new SslStream(new NetworkStream(socket));
                    await sslStream.AuthenticateAsClientAsync(address.Host);
                }
                else
                {
                    sslStream = new SslStream(new NetworkStream(socket), false, ssl.RemoteCertificateValidationCallback, ssl.LocalCertificateSelectionCallback);
                    await sslStream.AuthenticateAsClientAsync(address.Host, ssl.ClientCertificates,
                        ssl.Protocols, ssl.CheckCertificateRevocation);
                }

                transport = new SslSocket(this, sslStream);
            }
            else
            {
                transport = new TcpSocket(this, socket);
            }

            this.socketTransport = transport;
            this.writer = new Writer(this, this.socketTransport);
        }
示例#34
0
        static void Main(string[] args)
        {
            Amqp.Trace.TraceLevel = Amqp.TraceLevel.Frame | Amqp.TraceLevel.Verbose;
            Amqp.Trace.TraceListener = (f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));

            address = new Address(HOST, PORT, null, null);
            connection = new Connection(address);

            session = new Session(connection);

            SendCommand();
            receiverThread = new Thread(ReceiveFeedback);
            receiverThread.Start();

            // just as example ...
            // the application ends only after received a command or timeout on receiving
            receiverThread.Join();

            session.Close();
            connection.Close();
        }
 public E2EAmqpTransactionTest() : base()
 {
     address = new Amqp.Address($"{base.publisherSettings.Protocol}://{base.publisherSettings.PolicyName}:{base.publisherSettings.Key}@{base.publisherSettings.Namespace}");
     path    = base.publisherSettings.Topic;
 }