예제 #1
0
        /// <summary>
        ///     Creates a new connection with the given user name and password
        /// </summary>
        public IConnection CreateConnection()
        {
            Connection connection = null;

            try
            {
                var transport = _transportFactory.CreateTransport(BrokerUri);
                connection = new Connection(BrokerUri, transport, ClientIdGenerator, StompConnectionSettings);

                ConfigureConnection(connection);

                // Set the client id if set
                if (StompConnectionSettings.ClientId.IsNotEmpty())
                {
                    connection.DefaultClientId = StompConnectionSettings.ClientId;
                }

                return(connection);
            }
            catch (Exception ex)
            {
                try
                {
                    connection?.Close();
                }
                catch
                {
                    // ignored
                }

                throw new StompException($"Could not connect to broker URL: '{BrokerUri}'. See inner exception for details.", ex);
            }
        }
예제 #2
0
        private async Task StartTransport(Uri connectUrl, TransportType transportType, TransferFormat transferFormat)
        {
            // Create the pipe pair (Application's writer is connected to Transport's reader, and vice versa)
            var options = new PipeOptions(writerScheduler: PipeScheduler.ThreadPool, readerScheduler: PipeScheduler.ThreadPool, useSynchronizationContext: false);
            var pair    = DuplexPipe.CreateConnectionPair(options, options);

            // Construct the transport
            var transport = _transportFactory.CreateTransport(transportType);

            // Start the transport, giving it one end of the pipe
            try
            {
                await transport.StartAsync(connectUrl, pair.Application, transferFormat, this);
            }
            catch (Exception ex)
            {
                Log.ErrorStartingTransport(_logger, transport, ex);
                _transport = null;
                throw;
            }

            // We successfully started, set the transport properties (we don't want to set these until the transport is definitely running).
            _transport     = transport;
            _transportPipe = pair.Transport;

            Log.TransportStarted(_logger, _transport);
        }
        public void Init(InitialDeviceConfig config)
        {
            InitDeviceInfo(config);

            Transport            = TransportFactory.CreateTransport(this);
            _telemetryController = TelemetryFactory.PopulateDeviceWithTelemetryEvents(this);

            InitCommandProcessors();
        }
예제 #4
0
        private async Task <List <Task> > StartDeliveriesAsync(List <Task> createDeliveryTasks, TransportTypes transportType)
        {
            var dronesTasks = new List <Task>();

            while (createDeliveryTasks.Count > 0)
            {
                Task finishedTask = await Task.WhenAny(createDeliveryTasks);

                if (finishedTask.Exception is not null)
                {
                    await ManageFailedTaskAsync(finishedTask);
                }
                else
                {
                    var delivery  = ((Task <Delivery>)finishedTask).Result;
                    var transport = transportFactory.CreateTransport(transportType);
                    dronesTasks.Add(transport.DeliverAsync(fileManager, delivery));
                }

                createDeliveryTasks.Remove(finishedTask);
            }
            return(dronesTasks);
        }
예제 #5
0
        public MTProtoConnection(TransportConfig transportConfig, [NotNull] ITransportFactory transportFactory, [NotNull] TLRig tlRig,
                                 [NotNull] IMessageIdGenerator messageIdGenerator, [NotNull] IHashServices hashServices, [NotNull] IEncryptionServices encryptionServices)
        {
            Argument.IsNotNull(() => transportFactory);
            Argument.IsNotNull(() => tlRig);
            Argument.IsNotNull(() => messageIdGenerator);
            Argument.IsNotNull(() => hashServices);
            Argument.IsNotNull(() => encryptionServices);

            _transportFactory   = transportFactory;
            _tlRig              = tlRig;
            _messageIdGenerator = messageIdGenerator;
            _hashServices       = hashServices;
            _encryptionServices = encryptionServices;

            DefaultRpcTimeout     = Defaults.RpcTimeout;
            DefaultConnectTimeout = Defaults.ConnectTimeout;

            _tlRig.PrepareSerializersForAllTLObjectsInAssembly(typeof(ITLAsyncMethods).GetAssemblyEx());

            _sessionId = GetNextSessionId();

            // Init transport.
            _transport = _transportFactory.CreateTransport(transportConfig);

            // History of messages in/out.
            _inMessages.ObserveOn(DefaultScheduler.Instance).Subscribe(_inMessagesHistory);
            _outMessages.ObserveOn(DefaultScheduler.Instance).Subscribe(_outMessagesHistory);

            // Connector in/out.
            _transport.ObserveOn(DefaultScheduler.Instance).Do(bytes => LogMessageInOut(bytes, "IN")).Subscribe(ProcessIncomingMessageBytes);
            _outMessages.ObserveOn(DefaultScheduler.Instance)
            .Do(message => LogMessageInOut(message.MessageBytes, "OUT"))
            .Subscribe(message => _transport.Send(message.MessageBytes));

            _inMessages.ObserveOn(DefaultScheduler.Instance).Subscribe(ProcessIncomingMessage);
        }
예제 #6
0
 private void SyncTransport(EndPoint endPoint)
 {
     Logger.Debug("CreateTransport:{0} ", endPoint);
     _transportFactory.CreateTransport(endPoint);
 }
예제 #7
0
        /// <summary>
        /// Creates a normal transport.
        /// </summary>
        /// <param name="location"></param>
        /// <returns>the transport</returns>
        public static ITransport CreateTransport(Uri location)
        {
            ITransportFactory tf = TransportFactory.CreateTransportFactory(location);

            return(tf.CreateTransport(location));
        }
예제 #8
0
        /// <summary>
        ///     Check and ensure that the connection objcet is connected.  If it is not
        ///     connected or is closed, a ConnectionClosedException is thrown.
        /// </summary>
        private void CheckConnected()
        {
            if (_closed.Value)
            {
                throw new ConnectionClosedException();
            }

            if (_connected.Value)
            {
                return;
            }
            var timeoutTime = DateTime.Now + _stompConnectionSettings.RequestTimeout;
            var waitCount   = 1;

            while (true)
            {
                if (Monitor.TryEnter(_connectedLock))
                {
                    try
                    {
                        if (_closed.Value || _closing.Value)
                        {
                            break;
                        }
                        else if (!_connected.Value)
                        {
                            if (!_userSpecifiedClientId)
                            {
                                _info.ClientId = _clientIdGenerator.GenerateId();
                            }

                            try
                            {
                                if (null != Transport)
                                {
                                    // Make sure the transport is started.
                                    if (!Transport.IsStarted)
                                    {
                                        Transport.Start();
                                    }

                                    // Send the connection and see if an ack/nak is returned.
                                    var response = Transport.Request(_info, _stompConnectionSettings.RequestTimeout);
                                    if (!(response is ExceptionResponse))
                                    {
                                        _connected.Value = true;
                                    }
                                    else
                                    {
                                        var error     = response as ExceptionResponse;
                                        var exception = CreateExceptionFromBrokerError(error.Exception);
                                        // This is non-recoverable.
                                        // Shutdown the transport connection, and re-create it, but don't start it.
                                        // It will be started if the connection is re-attempted.
                                        Transport.Stop();
                                        var newTransport = _transportFactory.CreateTransport(BrokerUri);
                                        SetTransport(newTransport);
                                        throw exception;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Tracer.Error(ex);
                            }
                        }
                    }
                    finally
                    {
                        Monitor.Exit(_connectedLock);
                    }
                }

                if (_connected.Value || _closed.Value || _closing.Value || DateTime.Now > timeoutTime)
                {
                    break;
                }

                // Back off from being overly aggressive.  Having too many threads
                // aggressively trying to connect to a down broker pegs the CPU.
                Thread.Sleep(5 * waitCount++);
            }

            if (!_connected.Value)
            {
                throw new ConnectionClosedException();
            }
        }