Handling Socket WinRT Socket Errors

I am working on a streaming socket,

According to msdn documentaion:

Exception Handling

You must write code to handle exceptions when calling asynchronous methods in the StreamSocket class. Exceptions can be thrown due to parameter validation errors, name resolution errors, and network errors. Exceptions to network errors (such as loss of connectivity, connection failures, and server crashes) can occur at any time. These errors result in exceptions being thrown. If the application is not being processed, an exception can cause the entire application to terminate at runtime.

The Windows.Networking.Sockets namespace contains functions that make it easier to handle errors when using sockets. The GetStatus method in the SocketError class can convert an HRESULT from an exception to a SocketErrorStatus enumeration value. This can be useful for handling certain network exceptions differently in your application. An application can also use the exception HRESULT on parameter validation errors to find out more information about the error that caused the exception.

So, I used the following code to manage the states of the socket sockets.

  try
        {
            var socket = new StreamSocket();
            HostName host = new HostName("www.google.com");
            // connection is executed synchronously
            socket.ConnectAsync(host, "2000", SocketProtectionLevel.PlainSocket).AsTask().Wait();

            Debug.WriteLine("Success");
        }
        catch (Exception ex)
        {
            SocketErrorStatus socketErrorStatus = SocketError.GetStatus(ex.HResult);

            switch(socketErrorStatus)
            {
                case SocketErrorStatus.ConnectionTimedOut:
                    //do something
                    break;
                case SocketErrorStatus.HostNotFound:
                    //do something
                    break;
                default:
                    break;
            }
        }

      

But the exception object returned on socket error does not contain a valid HResult.

Below is the resulting exception object:

Count = The name "InnerExceptionCount" does not exist in the current context [System.AggregateException]: Count = The name "InnerExceptionCount" does not exist in the current context
Data : {System.Collections.ListDictionaryInternal}
HelpLink : null
HResult : -2146233088
InnerException: {System.Exception : The connection attempt was unsuccessful because the related party did not respond properly after a while, or the connection failed because the connected host was unable to respond. (Exception from HRESULT: 0x8007274C)}
Message: "One or more errors occurred."
Source : "mscorlib"
StackTrace: "at System.Threading.Tasks.Task.ThrowIfExceptional (Boolean includeTaskCanceledExceptions) \ r \ n at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout, CancellationToken cancelationToken) \ r \ n at System.Threading.Tasks.Task Wait () \ r \ n at StreamSokcetSample.MainPage.Button_Tapped (entity sender, TappedRoutedEventArgs e) "

In this situation, I always get SocketErrorStatus.Unknown (default) as the result, whereas passing int HRESULT: 0x8007274C to GetStatus results in correct output (ConnectionTimedOut = 3).

InnerException: {System.Exception: The connection attempt failed because the related party did not respond properly after a while, or the connection failed because the connected host was unable to respond. (Exception from HRESULT: 0x8007274C )}

Can I rely on the internal exception message and get the HRESULT from it?

Is there any other way to get the results you want?

+3


source to share


2 answers


You get AggregateException

as it is instantiated from the methodasync

So yes you should check HResult

InnerException



SocketErrorStatus socketErrorStatus = SocketError.GetStatus(ex.InnerException.HResult);

      

This will give you the desired result.

+1


source


The root exception is an AggregateException (this is a .NET layer exception), usually a wrapper exception for an exception thrown from another thread. In this case, it is because you were using the "ConnectAsync" method that was running on the thread pool.



So, in order to get the correct socket status, you have to use an InnerException that is thrown from the windows runtime layer.

0


source







All Articles