private Task <ConnAckPacket> AuthenticateAsync(ReadListeningHandler readListener, CancellationToken cancellationToken) { var packet = new ConnectPacket { ClientId = _options.ClientId, CleanSession = _options.CleanSession, KeepAlive = _options.KeepAlive, }; if (_options.Credentials != null) { packet.UsernameFlag = true; packet.UserName = _options.Credentials.Username; packet.Password = _options.Credentials.Username; } if (_options.WillMessage != null) { packet.WillFlag = true; packet.WillQos = _options.WillMessage.Qos; packet.WillRetain = _options.WillMessage.Retain; packet.WillTopic = _options.WillMessage.Topic; packet.WillMessage = _options.WillMessage.Payload; } return(SendAndReceiveAsync <ConnAckPacket>(packet, cancellationToken)); }
private async Task ReceivePacketsAsync(ReadListeningHandler clientReadListener, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { if (await clientReadListener.ReceiveAsync() is Packet packet) { await ProcessReceivedPacketAsync(packet); } } }
/// <summary> /// 读取Packet /// </summary> /// <param name="clientReadListener"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task TryReceivePacketsAsync(ReadListeningHandler clientReadListener, CancellationToken cancellationToken) { try { while (!cancellationToken.IsCancellationRequested) { if (await clientReadListener.ReceiveAsync() is Packet packet) { await TryProcessReceivedPacketAsync(packet); } } } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception while receiving packets."); } }
/// <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(); } }
/// <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"); } }
private void StartReceivingPackets(ReadListeningHandler clientReadListener, CancellationToken cancellationToken) { Task.Run(() => ReceivePacketsAsync(clientReadListener, cancellationToken)); }