首页 \ 问答 \ Stream Socket错误处理winRT(Stream Socket error handling winRT)

Stream Socket错误处理winRT(Stream Socket error handling winRT)

我正在使用流套接字,

根据msdn文档:

处理异常

在StreamSocket类上调用异步方法时,必须编写代码来处理异常。 参数验证错误,名称解析失败和网络错误可能导致异常。 网络错误(例如,连接丢失,连接失败和服务器故障)的例外情况可能随时发生。 这些错误导致抛出异常。 如果您的应用未处理,则异常可能导致整个应用程序被运行时终止。

Windows.Networking.Sockets命名空间具有在使用套接字时简化处理错误的功能。 SocketError类上的GetStatus方法可以将HRESULT从异常转换为SocketErrorStatus枚举值。 这对于在应用中以不同方式处理特定网络异常非常有用。 应用程序还可以使用来自参数验证错误的异常的HRESULT来了解有关导致异常的错误的更多详细信息。

所以我使用以下代码来处理套接字连接错误状态。

  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;
            }
        }

但是套接字错误返回的异常对象不包含有效的HResult。

以下是结果异常对象:

Count =当前上下文中不存在名称'InnerExceptionCount'[System.AggregateException]:Count =当前上下文中不存在名称'InnerExceptionCount'
数据 :{System.Collections.ListDictionaryInternal}
HelpLink :null
HResult :-2146233088
InnerException: {System.Exception:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应。 (HRESULT异常:0x8007274C)}
消息: “发生了一个或多个错误。”
资料来源 :“mscorlib”
StackTrace :“System.Threading.Tasks.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)\ r \ n在System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout,CancellationToken cancellationToken)\ r \ n在System.Threading.Tasks.Task .Wait()\ r \ n在StreamSokcetSample.MainPage.Button_Tapped(Object sender,TappedRoutedEventArgs e)“

在这种情况下,我总是得到SocketErrorStatus.Unknown(默认值)作为结果,而当我将HRESULT的:0x8007274C传递GetStatus时 ,它会产生正确的输出(ConnectionTimedOut = 3)。

InnerException: {System.Exception:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应。 ( HRESULT异常:0x8007274C )}

我可以依赖内部异常消息并从那里获取HRESULT吗?

有没有其他方法可以获得理想的结果?


I am working on stream socket,

According to msdn documentaion:

Handling exceptions

You must write code to handle exceptions when you call asynchronous methods on the StreamSocket class. Exceptions can result from parameter validation errors, name resolutions failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and server failures, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime.

The Windows.Networking.Sockets namespace has features that simplify handling errors when using sockets. The GetStatus method on the SocketError class can convert the HRESULT from an exception to a SocketErrorStatus enumeration value. This can be useful for handling specific network exceptions differently in your app. An app can also use the HRESULT from the exception on parameter validation errors to learn more detailed information on the error that caused the exception.

So I have used following code to handle socket connect error states.

  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 doesn't contain valid HResult.

Following is resultant 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: 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. (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 cancellationToken)\r\n at System.Threading.Tasks.Task.Wait()\r\n at StreamSokcetSample.MainPage.Button_Tapped(Object sender, TappedRoutedEventArgs e)"

In this situation I am always getting SocketErrorStatus.Unknown(default value) as result whereas when I pass int value of HRESULT: 0x8007274C to GetStatus, it results in correct output(ConnectionTimedOut = 3).

InnerException: {System.Exception: 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. (Exception from HRESULT: 0x8007274C)}

Can I rely upon inner exception message and fetch HRESULT from there?

Is there any other way to get desired results?


原文:https://stackoverflow.com/questions/31513254
更新时间:2023-09-25 06:09

最满意答案

我猜你想在这里knife node edit ,而不是knife edit node 。 在这种情况下,您可以在chef-repo的任何地方。


I'm guessing you want knife node edit here, rather than knife edit node. In that case, you can be anywhere in the chef-repo.

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。