Home > other >  C# Azure EventHub connection exception
C# Azure EventHub connection exception

Time:11-11

Hy Guys, i have a problem, unfortunately I'm trying to connect to the Azure EventHub but I always get an exception like:

System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. at Microsoft.Azure.Amqp.Transport.TransportStream.EndRead(IAsyncResult asyncResult) at Microsoft.Azure.Amqp.Transport.TransportStream.<>c__DisplayClass22_0.b__1(IAsyncResult a) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location --- at System.Net.Security.SslStream.g__InternalFillHandshakeBufferAsync|189_0[TIOAdapter](TIOAdapter adap, ValueTask1 task, Int32 minSize) at System.Net.Security.SslStream.ReceiveBlobAsync[TIOAdapter](TIOAdapter adapter) at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm) at System.Threading.Tasks.TaskToApm.End(IAsyncResult asyncResult) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) at Microsoft.Azure.Amqp.Transport.TlsTransport.HandleOpenComplete(IAsyncResult result, Boolean syncComplete) --- End of stack trace from previous location --- at Microsoft.Azure.Amqp.ExceptionDispatcher.Throw(Exception exception) at Microsoft.Azure.Amqp.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.Azure.Amqp.AmqpObject.OpenAsyncResult.End(IAsyncResult result) at Microsoft.Azure.Amqp.AmqpObject.EndOpen(IAsyncResult result) at Microsoft.Azure.Amqp.Transport.TlsTransportInitiator.HandleTransportOpened(IAsyncResult result) at Microsoft.Azure.Amqp.Transport.TlsTransportInitiator.OnTransportOpened(IAsyncResult result) --- End of stack trace from previous location --- at Microsoft.Azure.Amqp.ExceptionDispatcher.Throw(Exception exception) at Microsoft.Azure.Amqp.AsyncResult.End[TAsyncResult](IAsyncResult result) at Microsoft.Azure.Amqp.Transport.AmqpTransportInitiator.ConnectAsyncResult.End(IAsyncResult result) at Microsoft.Azure.Amqp.Transport.AmqpTransportInitiator.<>c.<ConnectAsync>b__17_1(IAsyncResult r) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location --- at Azure.Messaging.EventHubs.Amqp.AmqpConnectionScope.CreateAndOpenConnectionAsync(Version amqpVersion, Uri serviceEndpoint, Uri connectionEndpoint, EventHubsTransportType transportType, IWebProxy proxy, Int32 sendBufferSizeBytes, Int32 receiveBufferSizeBytes, RemoteCertificateValidationCallback certificateValidationCallback, String scopeIdentifier, TimeSpan timeout) at Microsoft.Azure.Amqp.FaultTolerantAmqpObject1.OnCreateAsync(TimeSpan timeout, CancellationToken cancellationToken) at Microsoft.Azure.Amqp.Singleton1.GetOrCreateAsync(TimeSpan timeout, CancellationToken cancellationToken) at Microsoft.Azure.Amqp.Singleton1.GetOrCreateAsync(TimeSpan timeout, CancellationToken cancellationToken) at Azure.Messaging.EventHubs.Amqp.AmqpConnectionScope.OpenManagementLinkAsync(TimeSpan operationTimeout, TimeSpan linkTimeout, CancellationToken cancellationToken) at Microsoft.Azure.Amqp.FaultTolerantAmqpObject1.OnCreateAsync(TimeSpan timeout, CancellationToken cancellationToken) at Microsoft.Azure.Amqp.Singleton1.GetOrCreateAsync(TimeSpan timeout, CancellationToken cancellationToken) at Microsoft.Azure.Amqp.Singleton`1.GetOrCreateAsync(TimeSpan timeout, CancellationToken cancellationToken) at Azure.Messaging.EventHubs.Amqp.AmqpClient.GetPropertiesAsync(EventHubsRetryPolicy retryPolicy, CancellationToken cancellationToken) at Azure.Messaging.EventHubs.Amqp.AmqpClient.GetPropertiesAsync(EventHubsRetryPolicy retryPolicy, CancellationToken cancellationToken) at Azure.Messaging.EventHubs.EventHubConnection.GetPropertiesAsync(EventHubsRetryPolicy retryPolicy, CancellationToken cancellationToken) at Azure.Messaging.EventHubs.EventHubConnection.GetPartitionIdsAsync(EventHubsRetryPolicy retryPolicy, CancellationToken cancellationToken) at Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient.GetPartitionIdsAsync(CancellationToken cancellationToken) at Program.Main() in C:\Users\f.daquila\RiderProjects\AuditLogRecevierSample\AuditLogRecevierSample\Program.cs:line 20 at Program.Main() in C:\Users\f.daquila\RiderProjects\AuditLogRecevierSample\AuditLogRecevierSample\Program.cs:line 41

The code with which I try to make the call is this:

class Program
{
    private const string eventHubConnectionString = "<CONNECTION STRING>";
    private const string consumerGroup = "<GROUP NAME>";
    
    
    public static async Task Main()
    {
        try
        {
            await using var consumer = new EventHubConsumerClient(consumerGroup, new EventHubConnection(eventHubConnectionString));
            var startingPosition = EventPosition.Earliest;

            var partitionIds = await consumer.GetPartitionIdsAsync();

            if (partitionIds is not null && partitionIds.Any())
            {
                var partitionId = partitionIds.First();
                using var cancellationSource = new CancellationTokenSource();
                cancellationSource.CancelAfter(TimeSpan.FromSeconds(45));

                await foreach (var receivedEvent in consumer.ReadEventsFromPartitionAsync(partitionId, startingPosition, cancellationSource.Token))
                {
                    var body = Encoding.UTF8.GetString(receivedEvent.Data.Body.ToArray());

                    Console.WriteLine(body);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}

I tried to see if there were any problems with the network using powershell by testing the connection like this:

enter image description here

and everything seems to be ok. What am I doing wrong? Why can't I connect?

A thousand thanks.

CodePudding user response:

The most common connection issue for persistent timeouts is that the ports needed for AMQP over TCP (5671/5672) are not open. This is often turns out to be the root cause even when Test-NetConnection succeeds.

Changing the transport to AMQP over WebSockets usually helps, as it will use port 443 and may be routed through a proxy, if needed. The transport can be specified using the EventHubConsumerClientOptions when creating your consumer:

var options = new EventHubConsumerClientOptions();
options.ConnectionOptions.TransportType = EventHubsTransportType.AmqpWebSockets;

await using var consumer = new EventHubConsumerClient(
    "<< CONSUMER GROUP >>",
    "<< CONNECTION STRING >>",
    "<< EVENT HUB NAME >>",
    options);

If that doesn't resolve the issue, I'd suggest taking a look at the Event Hubs troubleshooting guide for further steps.

A couple of other notable things about your snippet:

  • There's no reason to explicitly create an EventHubConnection unless you're creating multiple clients and would like to force them to share a single connection.

  • The return from GetPartitionIdsAsync will never be null and will always have at least one member. It is not possible to create an Event Hub with no partitions.

  • There's no need to explicitly decode the bytes for an event body. Using receivedEvent.Data.EventBody.ToString() would give you the same result.

  • The EventData.Body property is deprecated and is hidden; it exists only for backwards compatibility. We recommend using EventBody which provides additional functionality for working with binary data.

  • Related