javascript - JavaScript - 网络 ip 上的 Raspberry PI 的 XMLHttpRequest 在移动设备上失败,而不是在桌面上
问题描述
我的网络上有一个 Raspberry PI。我正在使用 WebSocket 连接到它并发送命令。我通过简单地调用这行代码来连接它:window.socket = new WebSocket(rpIP)
可能rpIP
是ws://10.58.3.146//ws
但是 PI 的 IP 是动态的,所以我使用客户端(javascript)在网络上扫描 PI。我已将 PI 设置为在端口 58 作为网络上唯一的设备进行响应。
我的逻辑是,如果我尝试向网络上所有可能的 255 个 IP 发出请求,则只有一个应该响应。这在桌面浏览器上效果很好。我找到了 PI,我可以向它发送命令。但是在移动设备上(我已经尝试过 Android 和 iOS)它失败了我收到以下错误:net::ERR_CONNECTION_REFUSED
扫描仪代码:
let myIp = '10.58.3.33';
let ipToCheck = 0;
let targetPort = 58;
let rpIP;
checkIp();
function checkIp() {
callError = false
if(ipToCheck < 255 && !rpIP) {
let ipArray = myIp.split('.');
ipArray[3] = ipToCheck;
addDebugMsg('Trying to connect to: ' + ipArray.join('.') + ':' + targetPort);
let loading = setInterval(function() {
addDebugMsg('.', false)
}, 500);
let request = new XMLHttpRequest();
request.open('GET', location.protocol + '//' + ipArray.join('.') + ':' + targetPort, true);
request.timeout = 1000;
request.onload = function(e) {
clearInterval(loading);
console.log(e)
if(request.status == 404) {
addDebugMsg('nope! - Pi\'s not here');
ipToCheck++;
checkIp();
} else {
addDebugMsg('YAY! - We found the Pi');
rpIP = protocol + '//' + ipArray.join('.') + '//ws';
ipToCheck++;
checkIp();
}
};
request.ontimeout = function() {
clearInterval(loading);
addDebugMsg('nope! - Pi\'s not here');
clearInterval(loading);
ipToCheck++;
checkIp();
}
request.send();
} else {
addDebugMsg('Scan done!');
if(rpIP) {
addDebugMsg('Found Rasberry PI at: ' + rpIP);
window.socket = new WebSocket(rpIP);
window.socket.onmessage = function(e) {
handleSocketMessage(e.data);
}
} else {
addDebugMsg('No Pi on network')
}
}
}
该addDebugMsg
功能只是我在找到 PI 时在页面上显示的功能。
解决方案
推荐阅读
- ios - UITableViewCell中带有图像的动态标签?
- python - 多目标预测
- java - 自动向 Jersey 客户端注册 ClientResponseFilter 和其他提供程序
- nativescript-vue - nativescript-fonticon 用于 nativescript-vue
- r - 带加权因变量的双向方差分析
- spring - 自动重试请求的 http 代码是什么?
- react-native - 错误在 macOS 中生成应用程序
- javascript - React 转换服务器响应(向对象添加额外字段)
- java - 如何知道 runtime.exec() 应用程序窗口是否处于活动状态(在 java 中)
- c# - 如何在 ASP.NET Core 中添加 Mime 类型