【问题标题】:Arduino client fails to connect to a hostname ServerArduino 客户端无法连接到主机名服务器
【发布时间】:2019-10-24 21:48:18
【问题描述】:

1.问题:

  • 我正在尝试使用本地 WiFi 连接两个 Arduino Nano33 IoT 主机名。
  • 我正在努力避免设置静态 IP 地址。
  • 使用 IP 地址连接时,整个程序运行良好。
  • 但是,当我尝试使用主机名连接到网络服务器 arduino 时,客户端无法连接。 (例如连接到 google.com 时除外)

2。这两种方法我都试过了:

客户端方法一:

char serverName[] = "ArduinoWebServer";
//char serverName[] = "google.com";         // if I use this as the serverName the client connects successfully

while (!client.connect(serverName,iPort)){
  Serial.println("Server not found");
  delay(5000);
}
if (client.connect(serverName,iPort)){
  Serial.println("Connected to Server");
}

客户端方法二:

  IPAddress ipServer;
  int err = WiFi.hostByName(serverName, ipServer) ;
  if(err == 1){
        Serial.print("Ip address: ");
        Serial.println(ipServer);
  } else {
        Serial.print("Error code: ");
        Serial.println(err);
  }

  while (!oClient.connect(ipServer,iPort)){
    Serial.println("Server not found");
    delay(5000);
  }
  if (oClient.connect(ipServer,iPort)){
    Serial.println("Connected to Server");
  }

服务器代码:

  WiFi.setHostname("ArduinoWebServer");
  //WiFi.config(ipServer);                // when using this instead of WiFi.setHostname the code works
  while (status != WL_CONNECTED){
    status = WiFi.begin(cSSID, cPass);

    if (status != WL_CONNECTED){
      Serial.println("Network not found, waiting to reconnect");
      delay(5000);
    }
  }
  oServer.begin();

有人知道解决这个问题吗?

【问题讨论】:

    标签: arduino android-wifi hostname


    【解决方案1】:

    您的 Arduino 设备可以访问 google.com,因为您的本地 DNS 服务器知道如何将此主机名解析为 IP 地址。但是您的本地 DNS 服务器不知道您分配给 Web 服务器的主机名。

    mDNS 旨在解决您的特定问题。

    这使用多播来解析以 .local

    结尾的域

    ESP8266 实现的示例代码位于 https://tttapa.github.io/ESP8266/Chap08%20-%20mDNS.html

    网络服务器将使用以下方式配置 mDNS 响应器:

    MDNS.begin("ArduinoWebServer")
    

    然后客户端可以使用主机名ArduinoWebServer.local进行连接

    【讨论】:

    • 感谢您的回复。我一定会试一试的。如果您介意的话,我有一些问题: 1. 我是否使用 mDNS 连接到网络而不是标准的 wifi.begin()? 2. 如果是这样,我说我必须在服务器和所有客户端上都使用 mDNS 是否正确? 3. 这是否适用于 Arduino Nano33 Iot?我没有看到它的库或 MKR1xxx 的库
    • 库和行#include 似乎与Arduino Nano33 IoT 不兼容。除非我错过了什么。
    • 我也尝试使用这里提出的 mDSNresolver:github.com/madpilot/mDNSResolver。我遇到了同样的图书馆问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多