【发布时间】:2021-02-25 22:25:10
【问题描述】:
我有一个运行网络服务器的 Arduino,它每 2 秒接收一次数据。我可以通过在浏览器中输入来连接到它的 IP 地址。我还创建了一个 Web 应用程序,每次有新数据进入时都会从该 IP 地址中提取数据。问题是我需要使用 Web 应用程序访问 IP 地址,而另一个程序正在访问它。目前一次只能访问一个程序。我想要一个 Python 脚本不断地从 IP 地址中提取数据,并且仍然允许 Web 应用程序连接以实时查看它。我怎样才能做到这一点?
删除了很多其他东西的 Arduino 代码...
WiFiServer server(80); //server socket
WiFiClient client_1 = server.available();
void setup() {
Serial.begin(9600);
enable_WiFi(); // function to enable wifi
connect_WiFi(); // function to connect to wifi
server.begin();
}
void loop() {
client_1 = server.available();
if (client_1) {
printWEB(client_1); // this posts the data as text to the web IP address
}
delay(2000);
}
void printWEB(WiFiClient client) {
if (client) { // if you get a client,
Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Access-Control-Allow-Origin: *");
client.println("Access-Control-Allow-Methods: GET");
client.println("Content-type: application/json");
client.println();
moistureReading = analogRead(A1);
tmpString = dataPosted;
tmpString.replace("%moistureData%", String(moistureReading) );
client.flush();
client.print( tmpString );
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else { // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
【问题讨论】:
-
好吧,你没有发布到 IP 地址让我们清楚,你有一个位于 IP 地址的“服务器”。为了给你一点帮助,我们必须知道你有什么类型的服务器。 “如果是”,它在什么操作系统上运行。服务器是在 Arduino 上还是在电脑上?
-
是的,这是一个 arduino mkr 1010 wifi。服务器通过 WiFiServer() 和 WiFiClient() 托管。这就是在设备上打开2个ip地址那么简单吗?
-
好的,等一下,我刚刚重读了您的评论!这是您用来上传数据的同一个 Arduino 和运行网络服务器的同一个 Arduino 吗?顺便说一句,如果可以的话,请将代码添加到您的问题中。
-
你只是为了澄清,我正在 arduino 上的指定 IP 地址打开一个 wifi 服务器。然后它通过wifi将数据发送到这个IP地址。在 arduino 之外,我有一个收集这些数据的网络应用程序。我只能通过单个连接连接到 IP 地址。如果我在应用程序运行时尝试对该 IP 地址运行一个单独的程序,它将无法打开。我尝试了一些简单的方法,例如使用PC在浏览器中打开IP地址并不断刷新,然后尝试通过手机打开IP地址,但它不起作用。如果我停止刷新 PC,手机就会连接。它不能处理多个请求
-
这有意义吗? IP 地址不能处理超过 1 个传入请求。我不确定代码在这种情况下是否会有所帮助,因为一切正常。这只是一个 IP 地址问题。
标签: http arduino webserver ip-address