Exemplo n.º 1
0
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public async ValueTask <MqttConnectResult> ConnectAsync(CancellationToken cancellationToken)
        {
            if (_eventLoop == null)
            {
                _eventLoop = new MultithreadEventLoopGroup();
            }

            var connectFuture = new TaskCompletionSource <MqttConnectResult>();
            var bootstrap     = new Bootstrap();

            bootstrap
            .Group(_eventLoop)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .RemoteAddress(Options.Host, Options.Port)
            .Handler(new MqttChannelInitializer(this, connectFuture));

            try
            {
                _channel = await bootstrap.ConnectAsync();

                if (_channel.Open)
                {
                    _packetDispatcher.Reset();
                    _packetIdProvider.Reset();
                    IsConnected = true;
                }
                return(await connectFuture.Task);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                throw new MqttException("BrokerUnavailable: " + ex.Message);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public async Task <ConnectReturnCode> ConnectAsync()
        {
            var clientReadListener = new ReadListeningHandler();
            var bootstrap          = new Bootstrap();

            bootstrap
            .Group(_group)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
            {
                ch.Pipeline.AddLast(MqttEncoder.Instance, new MqttDecoder(false, 256 * 1024), clientReadListener);
            }));

            try
            {
                _packetDispatcher.Reset();
                _packetIdProvider.Reset();
                _cancellationTokenSource = new CancellationTokenSource();
                _clientChannel           = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(_options.Host), _options.Port));

                _packetReceiverTask = Task.Run(() => TryReceivePacketsAsync(clientReadListener, _cancellationTokenSource.Token));

                var connectResponse = await AuthenticateAsync().ConfigureAwait(false);

                if (connectResponse.ConnectReturnCode == ConnectReturnCode.ConnectionAccepted)
                {
                    OnConnected?.Invoke(connectResponse.ConnectReturnCode);
                }

                return(connectResponse.ConnectReturnCode);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                throw new MqttException("BrokerUnavailable");
            }
            finally
            {
                await DisconnectAsync();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public async Task <ConnectReturnCode> ConnectAsync()
        {
            var clientReadListener = new ReadListeningHandler();
            var bootstrap          = new Bootstrap();

            bootstrap
            .Group(_eventLoopGroup)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddLast(MqttEncoder2.Instance, new MqttDecoder2(false, 256 * 1024), clientReadListener);
            }));

            try
            {
                _packetDispatcher.Reset();
                _packetIdentifierProvider.Reset();
                _cancellationTokenSource = new CancellationTokenSource();

                _clientChannel = await bootstrap.ConnectAsync(_options.Host, _options.Port);

                StartReceivingPackets(clientReadListener, _cancellationTokenSource.Token);

                var connectResponse = await AuthenticateAsync(clientReadListener, _cancellationTokenSource.Token);;
                if (connectResponse.ConnectReturnCode == ConnectReturnCode.ConnectionAccepted)
                {
                    Connected.Invoke(this, new MqttClientConnectedEventArgs(connectResponse.SessionPresent));
                }
                return(connectResponse.ConnectReturnCode);
            }
            catch
            {
                await DisconnectAsync();

                throw new MqttException("BrokerUnavailable");
            }
        }