无法使用 Arduino ESP8266 或兼容板连接到 LocalIP 或 Localhost (127.0.0.1)

Cannot connect to LocalIP or Localhost (127.0.0.1) Using Arduino ESP8266 or Compatible Boards

我正在尝试将我的 Arduino ESP8266 或任何兼容板(如 WeMos mini 或 NodeMCU)与我的本地服务器 localhost(127.0.0.1)172.xx.xx.xxx port 80 连接,我得到一个 httpResponseCode - 1 个错误。但是如果我将它连接到远程服务器,我会得到一个 httpResponseCode 200 (OK).

我是 运行 一个 XMPP 服务器(甚至用 Coldfusion 服务器测试过)我的代码如下。有人可以帮忙吗?

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const char* ssid = "ssid";
const char* password = "password";

//Your Domain name with URL path or IP address with path
String serverName = "http://whosebug.com";// returns 200 (ok results)
//String serverName = "127.0.0.1"; // Gives -1 error, Tried IP addresses with 172.xx.xx.xx or even 192.168.xx.xx.

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
// unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200); 
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if (WiFi.status() == WL_CONNECTED){
      HTTPClient http;
      String serverPath = serverName + "?temperature=24.37";
      // Your Domain name with URL path or IP address with path
      //http.begin(serverPath.c_str());
        http.begin(serverName);
      // Send HTTP GET request
        int httpResponseCode = http.GET();
      
        if (httpResponseCode>0) {
          Serial.print("HTTP Response code: ");
          Serial.println(httpResponseCode);
          String payload = http.getString();
          Serial.println(payload);
        } else {
          Serial.print("Error code: ");
          Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    } else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

127.0.0.1 是 Arduino 本身,不是您的本地服务器。

每一台有IP地址的主机/电脑也有一个IP地址127.0.0.1;它是环回接口的地址。

localhost 地址始终指的是 当前计算机 。 Arduino也有这个地址,你正在尝试连接它。

使用您的 XMPP 服务器的 IP 地址;首先找出地址是什么,这比猜测和尝试要好得多。