简体   繁体   English

Win10 IOT / UWP:如何检测网络设备(Arduino)是否可用

[英]Win10 IOT / UWP: How to detect if a network device (Arduino) is availabe

I'd like to connect if my Arduino is available on the network. 如果我的Arduino在网络上可用,我想连接。 I'm trying to access the Arduino web server using an HTTP client and processing the JSON answer. 我正在尝试使用HTTP客户端访问Arduino Web服务器并处理JSON答案。

Since ping is not available in UWP what are my options? 由于在UWP中无法使用ping,我有什么选择? (see: Article ) (请参阅: 文章

One option would be to handle the exception of the HTTP client. 一种选择是处理HTTP客户端的异常。 But is there any more elegant way to check the connection before requesting the JSON data? 但是,在请求JSON数据之前,还有其他更优雅的方法来检查连接吗?

One method might be using the HTTPClient to do a GetAsync() and check the Status code coming out of it. 一种方法可能是使用HTTPClient执行GetAsync()并检查发出的状态代码。

Depending on your time constraints, you can wait for it to time out naturally or pass a cancellation token to break it sooner than the defaults. 根据您的时间限制,您可以等待它自然超时,或者传递取消令牌以使其比默认值更早破解。

From here https://docs.microsoft.com/en-us/windows/uwp/networking/httpclient (slightly modified): 从这里https://docs.microsoft.com/zh-cn/windows/uwp/networking/httpclient (稍作修改):

//Send the GET request asynchronously and retrieve the response as a string.

Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = "";

try
{
    //Send the GET request
    httpResponse = await httpClient.GetAsync(requestUri);
    if(httpResponse.IsSuccessStatusCode) { /* Do something with it */ }
    else { /* Do fallback here */ }
}
catch (Exception ex)
{
    httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM