NodeMcu arduino ESP8266WIFI 模块 WIFIClienBasic(TCP服务器发送信息)
流程
- 配置连接网络
- 发送TCP请求
- 获取接受数据打印
/*
This sketch sends a string to a TCP server, and prints a one-line response.
You must run a TCP server in your local network.
For example, on Linux you can use this command: nc -v -l 3000
该程序向TCP服务器发送一个字符串,并打印一行响应。
您必须在本地网络中运行TCP服务器。
例如,在Linux上,可以使用以下命令:nc-v-l 3000
*/
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#ifndef STASSID
#define STASSID "dajiating"
#define STAPSK "DJTxxxxx"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "www.baidu.com";
const uint16_t port = 80;
ESP8266WiFiMulti WiFiMulti;
//配置网络连接
void setup() {
Serial.begin(115200);
// We start by connecting to a WiFi network
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
Serial.println();
Serial.println();
Serial.print("Wait for WiFi... ");
while (WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
//开始发送请求获取数据
void loop() {
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
//用 WiFiClient 类以创建TCP连接
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
Serial.println("wait 5 sec...");
delay(5000);
return;
}
// This will send the request to the server
//将会向服务器发送请求
//client.println("hello from ESP8266");
//取消下行注释,发送一个基本的文档请求到服务器
client.print("GET /index/html HTTP/1.1\n\n");
//read back one line from server
//读取服务器响应内容
//直接相应数据
// Serial.println("receiving from remote server");
// String line = client.readStringUntil('\r');
// Serial.println(line);
//循环等待接受数据
int maxloops = 0;
//等待服务器响应
while (!client.available() && maxloops < 1000)
{
maxloops++;
delay(1); //延时 1 ms
}
if (client.available() > 0)
{
//读取服务器响应内容
while(client.available()) { //检测接收缓存区是否有内容
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
else
{
Serial.println("client.available() timed out ");
}
Serial.println("closing connection");
client.stop();
Serial.println("wait 5 sec...");
delay(5000);
}