public Task <int> ReceiveAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken) { if (buffer.Array == null) { throw new ArgumentNullException(nameof(buffer)); } cancellationToken.ThrowIfCancellationRequested(); using (cancellationToken.Register(() => _udpTransport.Close())) { try { var received = _dtlsTransport.Receive(buffer.Array, buffer.Offset, buffer.Count, 0); return(Task.FromResult(received)); } catch (ObjectDisposedException) { return(Task.FromResult(0)); } catch (SocketException) { return(Task.FromResult(0)); } } }
public async Task ConnectAsync(CoapTransportLayerConnectOptions connectOptions, CancellationToken cancellationToken) { if (connectOptions == null) { throw new ArgumentNullException(nameof(connectOptions)); } cancellationToken.ThrowIfCancellationRequested(); try { _udpTransport = new UdpTransport(connectOptions); var clientProtocol = new DtlsClientProtocol(_secureRandom); _dtlsClient = new DtlsClient(ConvertProtocolVersion(DtlsVersion), (PreSharedKey)Credentials); using (cancellationToken.Register(() => { _udpTransport.Close(); })) { _dtlsTransport = await Task.Run(() => clientProtocol.Connect(_dtlsClient, _udpTransport), cancellationToken).ConfigureAwait(false); } } catch { _udpTransport?.Dispose(); if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(); } if (_dtlsClient.ReceivedAlert != 0) { throw new DtlsException($"Received alert {AlertDescription.GetText(_dtlsClient.ReceivedAlert)}.", null) { ReceivedAlert = _dtlsClient.ReceivedAlert }; } throw; } }