#include <SPI.h>
#include <Ethernet.h>
#include <ArduinoJson.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 33, 166);
char serverName[] = "120.24.xx.77";
EthernetClient client;
DynamicJsonDocument doc(110);
char json[200];
int i = 0;
int count = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("start...");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
}
void loop() {
//delay(1000);
count = 0;
i = 0;
if (client.connect(serverName, 8066)) {
Serial.println("connected");
client.println("GET /user/123 HTTP/1.1");
client.println("Host: 120.24.60.77:8066");
client.println("Connection: close");
client.println();
} else {
Serial.println("connection failed");
}
//此处需要等待一段时间,不然没有获取到数据,下面的程序无法进入执行就又重新发起请求了,永远读取不到数据了
delay(100);
Serial.println("connecting...");
while (client.available()) {
char c = client.read();
Serial.print(c);
if ('\n' == c) {
count++;
}
if (count >= 10 && count < 11) {
json[i++] = c;
}
}
if (!client.connected()) {
Serial.print("count:");
Serial.println(count);
Serial.println("--------------1");
Serial.println(json);
Serial.println("--------------2");
DeserializationError err = deserializeJson(doc, json);
if (err) {
Serial.print("Error:");
Serial.print(err.c_str());
}
JsonObject obj = doc.as<JsonObject>();
String msg = obj["message"];
Serial.println(msg);
Serial.println("disconnecting.");
//client.stop();
//while (true);
//delay(1000);
}
}
|