美好的一天!我的代码有问题。当我连接到我的Web服务器时,为什么我的连接失败了。顺便说一下,我正在使用NodeMCU。希望你们能帮助我。提前谢谢。
答案 0 :(得分:1)
提供完整的代码会很有帮助。另外,我可以看到你正在参与ESP8266软件包中提供的WiFiClient草图,至少对我来说是Arduino IDE。如果我错了(你没有使用那个草图)那么试试这个:
#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "stackoverflow.com";
const char* streamId = "....................";
const char* privateKey = "....................";
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
int value = 0;
void loop() {
delay(5000);
++value;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/";
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
我已修改此内容以获取stackoverflow.com的主页。当然,您需要提供SSID和SSID密码并指定主机名。
如果您需要帮助为Arduino IDE安装ESP8266 / NodeMCU库,请查看:https://www.teachmemicro.com/intro-nodemcu-arduino/