NodeMcu arduino ESP8266WIFI 模块 WIFIClient示例介绍 使用WiFiClient 连接tcp服务

本文介绍如何使用NodeMCU和ESP8266模块通过WiFi连接服务器并收发数据。文章详细解释了setup()和loop()函数的作用,展示了如何利用WiFiClient类建立TCP连接,并提供了完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初次使用NodeMcu arduino,由于自己只有esp8266 -2.4G 模块 所以后面会吧 esp8266wifi 示例说明万,所有的函数类库均会注释说明,方便后期自己的理解,至于NodeMcu 类库后面会针对esp8266 -2.4G 说明几个常用的。自己写的有问题的,可以留言或者私信,方便改正。

WiFi子系统由必须定期运行的后台任务维护。任何花费超过15毫秒(毫秒)的功能或任务 都可能导致WiFi子系统崩溃。为了避免这些潜在的崩溃,建议WiFi子系统在执行超过 15ms指南的任何任务或功能之前,使用wifi.suspend ()挂起。

以下示例来源于 NodeMcu arduino 平台。

/*当程序开始执行时,将调用setup()函数,使用它来初始化变量,引脚模式,开始使用库等。设置功能仅在 Arduino 板的每次通电或复位后运行一次。使用此函数,类似于起始函数。与stm32的main函数相似的*/
void setup() {
  // put your setup code here, to run once:

}

/*在创建一个 setup() 函数(初始化并设置初始值)之后,loop() 函数将按照其名称的含义执行,并连续循环,从而允许程序进行更改和响应。使用它来主动控制arduino板。连续执行函数内的语句.写一些需要循环操作的逻辑代码*/
void loop() {
  // put your main code here, to run repeatedly:

}

WIFIClient 示例说明

/*
    This sketch establishes a TCP connection to a "quote of the day" service.
    It sends a "hello" message, and then prints received data.
   创建一个客戶端,该客戶端可以连接接到 client.connect() 中定义的指定 Internet IP 地址和端口。它发送一条“hello”消息,然后打印接收到的数据。
*/
#include <ESP8266WiFi.h>

#ifndef STASSID
#define STASSID "your-ssid"           //你的无线网络名称
#define STAPSK  "your-password"       //你的无线密码
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "djxmmx.net";      //需要请求的网络地址IP/网址
const uint16_t port = 8081;           //端口号,80,443,自定义的端口8081

void setup() {
  /*Arduino 串口通讯会用到 Stream 这个类(Serial)
  串口其实就是一种通讯方式的称呼,背后隐藏的实质是一种数据传输协议。数据一位一位地发送出去和接收进来。
  Stream 类是二进制数据或者字符串数据流传输的基础类
  */
  
  //该函数 begint() 设置串口数据传输的波特率。并打印到串口监视器上。
  Serial.begin(115200);  //初始化串口设置

  // We start by connecting to a WiFi network--我们从连接WiFi网络开始
  //Arduino 的输出基本就用两个函数 print 和 println,区别在于后者比前者多了回车换行
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
     would try to act as both a client and an access-point and could cause
     network-issues with your other WiFi-devices on your WiFi-network.
	WiFi模块分为两个工作模式AP与STA
 */
 
  WiFi.mode(WIFI_STA);  //设置ESP8266工作模式为无线终端模式
  WiFi.begin(ssid, password);  //开始连接wifi

  while (WiFi.status() != WL_CONNECTED) { //wifi处于已连接状态
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP()); //输出设备的IP地址
}

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; 
 /*WiFiClient 类
  创建一个客户端,该客户端可以连接到客户端.connect() 中定义的指定互联网 IP 地址和端口。
  WiFiClient库用于ESP8266的TCP协议物联网通讯.
  */
  if (!client.connect(host, port)) {  // 连接网络服务器
    Serial.println("connection failed");
    delay(5000);
    return;
  }

  // This will send a string to the server
  //译:这将向服务器发送字符串
  Serial.println("sending data to server");
  if (client.connected()) {  //connected()这个函数用于检查当前ESP8266与网络服务器的连接情况。如果连接成功,则返回“真”。否则返回“假”。
    client.println("hello from ESP8266"); // 连接成功后串口输出“hello from ESP8266”信息
  }

  // wait for data to be available
  //译,等待返回数据状态
  unsigned long timeout = millis();
  while (client.available() == 0) { //available()这个函数在有数据接收到并且没有读取完的时候,则会返回“真”,否则返回“假”。
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      delay(60000);
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  //译:从服务器读取回复的所有行,并将其打印到Serial
  Serial.println("receiving from remote server");
  // not testing 'client.connected()' since we do not need to send data here
  //译:不测试'客户端。connected()',因为我们不需要在此处发送数据
  while (client.available()) { //available()这个函数在有数据接收到并且没有读取完的时候,则会返回“真”,否则返回“假”。
    char ch = static_cast<char>(client.read());  read()//函数可用于从设备接收到的数据中读取信息。读取到的数据信息将以字符串形式返回。当函数读取到终止字符后,会立即停止函数执行。此时函数所返回的字符串为”终止字符”前的所有字符信息。
    Serial.print(ch);
  }

  // Close the connection
  Serial.println();
  Serial.println("closing connection");
  client.stop(); // 关闭与服务器的连接

  delay(300000); // execute once every 5 minutes, don't flood remote service
}

注*在ESP8266读取响应信息的过程中,服务端可能会断开与客服端的连接,所以这里使用了或。即便断开连接,只要有数据接收到并且没有读取完的时候,available()这个函数返回“真”,while循环语句体就会执行循环。
服务端报文发送完成后断开与客户端连接,连接断开并且读取完数据信息,则ESP8266跳出while循环。

### ESP8266 WiFi模块Arduino集成开发 #### 一、环境配置 为了使ESP8266连接Wi-Fi并使用Arduino IDE编程,需先安装必要的软件包和支持库。打开Arduino IDE,在首选项设置中添加ESP8266板管理器URL[^1]。 ```plaintext http://arduino.esp8266.com/stable/package_esp8266com_index.json ``` 随后通过`工具 -> 开发板 -> 板子管理器`来安装ESP8266平台支持文件。完成上述操作之后可以选择对应的ESP8266型号作为当前使用的开发板。 #### 二、基本示例连接至无线网络 下面给出一段简单的程序用于展示如何让ESP8266设备接入指定SSID和密码的Wi-Fi网络: ```cpp #include <ESP8266WiFi.h> const char* ssid = "your_SSID"; // 替换成实际路由器名称 const char* password = "your_PASSWORD";// 替换成对应密码 void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println("Connected!"); } void loop() {} ``` 此段代码实现了启动时尝试建立到给定AP热点之间的关联过程,并持续打印状态直到成功连网为止。 #### 三、高级应用:TCP客户端通信 对于更复杂的应用场景比如远程数据传输,则需要用到更高层次的功能——即创建一个TCP Client实例向服务器发送请求或接收响应消息。这里提供了一个利用`WiFiClient`类实现HTTP GET请求的例子[^2]: ```cpp #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> // 定义目标网站地址以及端口号 IPAddress serverIP(192, 168, 1, 177); // IP 地址形式的目标主机 int port = 80; // HTTP 默认端口 char* ssid = "your_SSID"; char* pass = "your_PASS"; void setup(){ Serial.begin(115200); WiFi.begin(ssid,pass); // 等待直至 Wi-Fi 成功连接... while(WiFi.status()!=WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); } void loop(){ WiFiClient client; const String request="GET /index.html HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"; if(client.connect(serverIP,port)){ Serial.println("connected."); client.print(request); while(client.connected()){ String line=client.readStringUntil('\r'); if(line=="\r"){ break; }else{ Serial.print(line); } } client.stop(); } delay(10000); // 每隔十秒执行一次查询动作 } ``` 这段脚本展示了怎样构建完整的HTTP协议报文并通过socket接口传递出去;同时也包含了处理来自webserver回复内容的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闰土小蒋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值