首页 > 解决方案 > JavaScript - 网络 ip 上的 Raspberry PI 的 XMLHttpRequest 在移动设备上失败,而不是在桌面上

问题描述

我的网络上有一个 Raspberry PI。我正在使用 WebSocket 连接到它并发送命令。我通过简单地调用这行代码来连接它:window.socket = new WebSocket(rpIP)可能rpIPws://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 时在页面上显示的功能。

标签: javascriptwebsocketgetraspberry-pixmlhttprequest

解决方案


推荐阅读