Win10 IOT/UWP:如何检测网络设备(Arduino)是否可用
问题描述:
如果我的Arduino在网络上可用,我想连接。我试图使用HTTP客户端访问Arduino Web服务器并处理JSON答案。Win10 IOT/UWP:如何检测网络设备(Arduino)是否可用
由于ping在UWP中不可用,我的选择是什么? (请参阅:Article)
一个选项是处理HTTP客户端的异常。但是在请求JSON数据之前有没有更好的方法来检查连接?
答
一种方法可能是使用HTTPClient来执行GetAsync()并检查出来的状态码。
根据您的时间限制,您可以等待它自然超时或传递取消标记,以便比默认值更快地分解它。
从这里https://docs.microsoft.com/en-us/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;
}
这是我目前的解决方案已经 - 我认为有可能是一个更优雅的在那里。 – Christoph