我是arduino的新手,正面临一个问题。我正在ardino中为ESP8266实现套接字。当我不使用delay()或不使用someFunction()时,它按预期工作。一旦我使用延迟或进行了一些处理,就比我断开连接断开了一个服务器套接字。
void loop(){
socketIO.loop();
uint64_t now = millis();
if(now - messageTimestamp > 2000) {
messageTimestamp = now;
// creat JSON message for Socket.IO (event)
DynamicJsonDocument doc(1024);
JsonArray array = doc.to<JsonArray>();
// add evnet name
// Hint: socket.on('event_name', ....
array.add("event_name");
// add payload (parameters) for the event
JsonObject param1 = array.createNestedObject();
param1["data"] = "Hello From Client";
// JSON to String (serializion)
String output;
serializeJson(doc, output);
// Send event
socketIO.sendEVENT(output);
// Print JSON for debugging
Serial.println(output);
}
//delay(10000); //if this delay is uncommented than i am not receving data on server but work fine if removed
//SomeFunction(); //if this SomeFunction (do some random work) is uncommented than i am not receving data on server but work fine if removed
}
您正在服务器端超时。
[制作delay(10000)
时,esp8266只是挂在某个循环上(作为延迟实现),因此此时不执行任何其他代码。因此,当服务器未获取任何数据时,它将断开与客户端的连接。
解决方案(简便方法)是每次您要发送数据时都建立一个新的连接。在伪代码中,它将如下所示:
void loop(){
connectToServer();
sendData();
Disconnect();
delay(1000);
SomeFunction();
}
然后它应该可以工作。
更复杂的方法是熟悉事件和回调的概念,并摆脱delay()
函数。或者尝试使用esp_rtos_sdk作为异步任务概念的RTOS框架。
开心!