The factory to create connections asynchronously.
Inheritance: Amqp.ConnectionFactoryBase
Beispiel #1
0
        static void Main(string[] args)
        {
            //Create host and register custom transport listener
            var uri = new Uri(address);
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.CustomTransports.Add("pipe", NamedPipeTransport.Listener);
            host.RegisterMessageProcessor(nodeName, new MessageProcessor());
            host.Open();
            Console.WriteLine("Listener: running");

            //Create factory with custom transport factory
            var factory = new ConnectionFactory(new TransportProvider[] { NamedPipeTransport.Factory });
            var connection = factory.CreateAsync(new Address(address)).GetAwaiter().GetResult();
            var session = new Session(connection);
            var sender = new SenderLink(session, "message-client", nodeName);
            Console.WriteLine("Client: sending a message");
            sender.Send(new Message("Hello Pipe!"));
            sender.Close();
            session.Close();
            connection.Close();
            Console.WriteLine("Client: closed");

            host.Close();
            Console.WriteLine("Listener: closed");
        }
        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();
        }
Beispiel #3
0
        static NmsConnectionInfo()
        {
            AmqpSettings defaultAmqpSettings = new Amqp.ConnectionFactory().AMQP;

            DEFAULT_CHANNEL_MAX    = defaultAmqpSettings.MaxSessionsPerConnection;
            DEFAULT_MAX_FRAME_SIZE = defaultAmqpSettings.MaxFrameSize;
            DEFAULT_IDLE_TIMEOUT   = defaultAmqpSettings.IdleTimeout;
        }
        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;
        }
        static ConnectionInfo()
        {
            Amqp.ConnectionFactory defaultCF           = new Amqp.ConnectionFactory();
            AmqpSettings           defaultAMQPSettings = defaultCF.AMQP;

            DEFAULT_CHANNEL_MAX    = defaultAMQPSettings.MaxSessionsPerConnection;
            DEFAULT_MAX_FRAME_SIZE = defaultAMQPSettings.MaxFrameSize;
            DEFAULT_IDLE_TIMEOUT   = defaultAMQPSettings.IdleTimeout;

            DEFAULT_REQUEST_TIMEOUT = Convert.ToInt64(NMSConstants.defaultRequestTimeout.TotalMilliseconds);
        }
Beispiel #6
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();
        }
Beispiel #7
0
        public ConnectionFactory(Uri brokerUri, string clientId, StringDictionary props)
        {
            impl          = new Amqp.ConnectionFactory();
            this.clientId = clientId;
            if (props != null)
            {
                this.InitApplicationProperties(props);
            }
            BrokerUri          = brokerUri;
            impl.AMQP.HostName = BrokerUri.Host;
            //
            // Set up tracing in AMQP.  We capture all AMQP traces in the TraceListener below
            // and map to NMS 'Tracer' logs as follows:
            //    AMQP          Tracer
            //    Verbose       Debug
            //    Frame         Debug
            //    Information   Info
            //    Output        Info    (should not happen)
            //    Warning       Warn
            //    Error         Error
            //
            Amqp.Trace.TraceLevel    = Amqp.TraceLevel.Verbose | Amqp.TraceLevel.Frame;
            Amqp.Trace.TraceListener = (level, format, args) =>
            {
                switch (level)
                {
                case Amqp.TraceLevel.Verbose:
                case Amqp.TraceLevel.Frame:
                    Tracer.DebugFormat(format, args);
                    break;

                case Amqp.TraceLevel.Information:
                case Amqp.TraceLevel.Output:
                    //
                    // Applications should not access AmqpLite directly so there
                    // should be no 'Output' level logs.
                    Tracer.InfoFormat(format, args);
                    break;

                case Amqp.TraceLevel.Warning:
                    Tracer.WarnFormat(format, args);
                    break;

                case Amqp.TraceLevel.Error:
                    Tracer.ErrorFormat(format, args);
                    break;

                default:
                    Tracer.InfoFormat("Unknown AMQP LogLevel: {}", level);
                    Tracer.InfoFormat(format, args);
                    break;
                }
            };
        }
Beispiel #8
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);
        }
        protected override void CopyBuilder(Amqp.ConnectionFactory copy)
        {
            base.CopyBuilder(copy);

            copy.SSL.Protocols = connectionBuilder.SSL.Protocols;
            copy.SSL.CheckCertificateRevocation = connectionBuilder.SSL.CheckCertificateRevocation;

            if (connectionBuilder.SSL.ClientCertificates != null)
            {
                copy.SSL.ClientCertificates = new X509CertificateCollection(connectionBuilder.SSL.ClientCertificates);
            }
        }
        public async Task <IConnection> CreateAsync(Endpoint endpoint, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            cancellationToken.Register(() => _tcs.TrySetCanceled());

            var connectionFactory = new Amqp.ConnectionFactory();
            var connection        = await connectionFactory.CreateAsync(endpoint.Address, null, OnOpened).ConfigureAwait(false);

            connection.AddClosedCallback(OnClosed);
            await _tcs.Task.ConfigureAwait(false);

            connection.Closed -= OnClosed;
            return(new Connection(_loggerFactory, endpoint, connection, _messageIdPolicyFactory));
        }
Beispiel #11
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;
        }
    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;
      }
    }
Beispiel #13
0
        internal void Configure(ConnectionFactory cf)
        {
            Amqp.ConnectionFactory cfImpl = cf.Factory as Amqp.ConnectionFactory;

            // get properties from connection factory
            StringDictionary properties = cf.ConnectionProperties;

            // apply connection properties to connection factory and connection info.
            PropertyUtil.SetProperties(cfImpl.AMQP, properties, ConnectionFactory.ConnectionPropertyPrefix);
            PropertyUtil.SetProperties(connInfo, properties, ConnectionFactory.ConnectionPropertyPrefix);

            // create copy of transport context
            this.transportContext = cf.Context.Copy();

            // Store raw properties for future objects
            this.properties = PropertyUtil.Clone(properties);

            // Create Connection builder delegate.
            this.implCreate = this.transportContext.CreateConnectionBuilder();
        }
Beispiel #14
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);
        }
        public void ContainerHostX509PrincipalTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            string address = "amqps://localhost:5676";
            X509Certificate2 cert = GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");
            ContainerHost sslHost = new ContainerHost(new Uri(address));
            sslHost.Listeners[0].SSL.Certificate = cert;
            sslHost.Listeners[0].SSL.ClientCertificateRequired = true;
            sslHost.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
            sslHost.Listeners[0].SASL.EnableExternalMechanism = true;
            ListenerLink link = null;
            var linkProcessor = new TestLinkProcessor();
            linkProcessor.OnLinkAttached += a => link = a;
            sslHost.RegisterLinkProcessor(linkProcessor);
            sslHost.Open();

            try
            {
                var factory = new ConnectionFactory();
                factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                factory.SSL.ClientCertificates.Add(cert);
                factory.SASL.Profile = SaslProfile.External;
                var connection = factory.CreateAsync(new Address(address)).Result;
                var session = new Session(connection);
                var sender = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();

                Assert.IsTrue(link != null, "link is null");
                var listenerConnection = (ListenerConnection)link.Session.Connection;
                Assert.IsTrue(listenerConnection.Principal != null, "principal is null");
                Assert.IsTrue(listenerConnection.Principal.Identity.AuthenticationType == "X509", "wrong auth type");

                X509Identity identity = (X509Identity)listenerConnection.Principal.Identity;
                Assert.IsTrue(identity.Certificate != null, "certificate is null");
            }
            finally
            {
                sslHost.Close();
            }
        }
 internal TransportContext()
 {
     connectionBuilder = new Amqp.ConnectionFactory();
     connectionBuilder.SASL.Profile = Amqp.Sasl.SaslProfile.Anonymous;
 }
Beispiel #17
0
        public async Task WebSocketSslMutalAuthTest()
        {
            string testName = "WebSocketSslMutalAuthTest";
            string listenAddress = "wss://localhost:18081/" + testName + "/";
            Uri uri = new Uri(listenAddress);

            X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");

            string output;
            int code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);
            if (code != 0)
            {
                string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
                    uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
                code = Exec("netsh.exe", args, out output);
                Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
            }

            X509Certificate serviceCert = null;
            X509Certificate clientCert = null;
            ListenerLink listenerLink = null;

            var linkProcessor = new TestLinkProcessor() { OnLinkAttached = c => listenerLink = c };
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.Listeners[0].SASL.EnableExternalMechanism = true;
            host.Listeners[0].SSL.ClientCertificateRequired = true;
            host.Listeners[0].SSL.CheckCertificateRevocation = true;
            host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return true; };
            host.RegisterLinkProcessor(linkProcessor);
            host.Open();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return true; };
                var wssFactory = new WebSocketTransportFactory();
                wssFactory.Options = o =>
                {
                    o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
                };

                ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
                connectionFactory.SASL.Profile = SaslProfile.External;
                Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");
                await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } });                
                await connection.CloseAsync();

                Assert.IsTrue(serviceCert != null, "service cert not received");
                Assert.IsTrue(clientCert != null, "client cert not received");
                Assert.IsTrue(listenerLink != null, "link not attached");

                IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
                Assert.IsTrue(principal != null, "connection pricipal is null");
                Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
            }
            finally
            {
                host.Close();
            }
        }
Beispiel #18
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();
        }
Beispiel #19
0
        public async Task CustomTransportConfiguration()
        {
            string testName = "CustomTransportConfiguration";

            ConnectionFactory factory = new ConnectionFactory();
            factory.TCP.NoDelay = true;
            factory.TCP.SendBufferSize = 16 * 1024;
            factory.TCP.SendTimeout = 30000;
            factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
            factory.AMQP.MaxFrameSize = 64 * 1024;
            factory.AMQP.HostName = "contoso.com";
            factory.AMQP.ContainerId = "container:" + testName;

            Address sslAddress = new Address("amqps://*****:*****@127.0.0.1:5671");
            Connection connection = await factory.CreateAsync(sslAddress);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);

            Message message = new Message("custom transport config");
            message.Properties = new Properties() { MessageId = testName };
            await sender.SendAsync(message);

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            Message message2 = await receiver.ReceiveAsync();
            Assert.IsTrue(message2 != null, "no message received");
            receiver.Accept(message2);

            await connection.CloseAsync();
        }
Beispiel #20
0
 public void Connect(Connection connection, Address address, bool noVerification)
 {
     this.connection = connection;
     var factory = new ConnectionFactory();
     this.ConnectAsync(address, factory).ConfigureAwait(false).GetAwaiter().GetResult();
 }
        public void ContainerHostCustomTransportTest()
        {
            string name = "ContainerHostCustomTransportTest";
            string address = "pipe://./" + name;
            ContainerHost host = new ContainerHost(new Uri(address));
            host.CustomTransports.Add("pipe", NamedPipeTransport.Listener);
            host.RegisterMessageProcessor(name, new TestMessageProcessor());
            host.Open();

            try
            {
                var factory = new ConnectionFactory(new TransportProvider[] { NamedPipeTransport.Factory });
                var connection = factory.CreateAsync(new Address(address)).GetAwaiter().GetResult();
                var session = new Session(connection);
                var sender = new SenderLink(session, name, name);
                sender.Send(new Message("msg1"), SendTimeout);
                connection.Close();
            }
            finally
            {
                host.Close();
            }
        }
Beispiel #22
0
            protected Connection CreateConnection(Address address)
            {
                var factory = new ConnectionFactory();
                if (address.Scheme.Equals("amqps", StringComparison.OrdinalIgnoreCase))
                {
                    factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                }

                return factory.CreateAsync(address).Result;
            }
Beispiel #23
0
            protected Connection CreateConnection(Address address)
            {
                var factory = new ConnectionFactory();
                factory.BufferManager = this.bufferManager;
                factory.AMQP.MaxFrameSize = this.perfArgs.MaxFrameSize;
                if (address.Scheme.Equals("amqps", StringComparison.OrdinalIgnoreCase))
                {
                    factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
                }

                return factory.CreateAsync(address).Result;
            }
Beispiel #24
0
        public async Task ConnectAsync(Address address, ConnectionFactory factory)
        {
            IPAddress[] ipAddresses;
            IPAddress ip;
            if (IPAddress.TryParse(address.Host, out ip))
            {
                ipAddresses = new IPAddress[] { ip };
            }
            else
            {
                ipAddresses = await TaskExtensions.GetHostAddressesAsync(address.Host);
            }

            // need to handle both IPv4 and IPv6
            Socket socket = null;
            Exception exception = null;
            for (int i = 0; i < ipAddresses.Length; i++)
            {
                if (ipAddresses[i] == null ||
                    (ipAddresses[i].AddressFamily == AddressFamily.InterNetwork && !Socket.OSSupportsIPv4) ||
                    (ipAddresses[i].AddressFamily == AddressFamily.InterNetworkV6 && !Socket.OSSupportsIPv6))
                {
                    continue;
                }

                socket = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    await socket.ConnectAsync(ipAddresses[i], address.Port);
                    exception = null;
                    break;
                }
                catch (Exception e)
                {
                    exception = e;
                    socket.Dispose();
                    socket = null;
                }
            }

            if (socket == null)
            {
                throw exception ?? new SocketException((int)SocketError.AddressNotAvailable);
            }

            if (factory.tcpSettings != null)
            {
                factory.tcpSettings.Configure(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);
        }
            public async void Start(string address)
            {
                ConnectionFactory factory = new ConnectionFactory();

                try
                {
                    this.connection = await factory.CreateAsync(new Address(address));
                    this.session = new Session(connection);
                    this.sender = new SenderLink(session, "send-link", "control");
                    this.receiver = new ReceiverLink(session, "recv-link", "data");
                    this.receiver.Start(50, this.OnMessage);
                }
                catch
                {
                    this.Message = "err:2";
                }
            }
            public async void Start()
            {
                Address address = new Address("amqp://*****:*****@192.168.1.120:5672");
                ConnectionFactory factory = new ConnectionFactory();

                try
                {
                    this.connection = await factory.CreateAsync(address);
                    this.session = new Session(connection);
                    this.sender = new SenderLink(session, "send-link", "control");
                    this.receiver = new ReceiverLink(session, "recv-link", "data");
                    this.receiver.Start(50, this.OnMessage);
                }
                catch
                {
                    this.Message = "err:2";
                }
            }
Beispiel #27
0
        static void Main(string[] args)
        {
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a));

            string address = "amqps://localhost:5671";

            // start a host with custom SSL and SASL settings
            Console.WriteLine("Starting server...");
            Uri addressUri = new Uri(address);
            ContainerHost host = new ContainerHost(addressUri);
            var listener = host.Listeners[0];
            listener.SSL.Certificate = GetCertificate("localhost");
            listener.SSL.ClientCertificateRequired = true;
            listener.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            listener.SASL.EnableExternalMechanism = true;
            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            string messageProcessor = "message_processor";
            host.RegisterMessageProcessor(messageProcessor, new MessageProcessor());
            Console.WriteLine("Message processor is registered on {0}", messageProcessor);

            Console.WriteLine("Starting client...");
            ConnectionFactory factory = new ConnectionFactory();
            factory.SSL.ClientCertificates.Add(GetCertificate("localhost"));
            factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            factory.SASL.Profile = SaslProfile.External;
            Console.WriteLine("Sending message...");
            Connection connection = factory.CreateAsync(new Address(address)).Result;
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "certificate-example-sender", "message_processor");
            sender.Send(new Message("hello world"));
            sender.Close();
            session.Close();
            connection.Close();
            Console.WriteLine("client done");

            host.Close();
            Console.WriteLine("server stopped");
        }
        public void ContainerHostSaslAnonymousTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            ListenerLink link = null;
            var linkProcessor = new TestLinkProcessor();
            linkProcessor.OnLinkAttached += a => link = a;
            this.host.RegisterLinkProcessor(linkProcessor);

            var factory = new ConnectionFactory();
            factory.SASL.Profile = SaslProfile.Anonymous;
            var connection = factory.CreateAsync(new Address(Address.Host, Address.Port, null, null, "/", Address.Scheme)).Result;
            var session = new Session(connection);
            var sender = new SenderLink(session, name, name);
            sender.Send(new Message("msg1"), SendTimeout);
            connection.Close();

            Assert.IsTrue(link != null, "link is null");
            var listenerConnection = (ListenerConnection)link.Session.Connection;
            Assert.IsTrue(listenerConnection.Principal == null, "principal should be null");
        }