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

初次使用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循环。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个简单的示例代码,演示如何在两个ESP8266 wifi模块之间通过TCP连接进行通信。其中一个ESP8266 wifi模块作为TCP服务器,另一个ESP8266 wifi模块作为TCP客户端。 TCP服务器端代码: ``` #include <ESP8266WiFi.h> const char* ssid = "YourWiFiSSID"; const char* password = "YourWiFiPassword"; WiFiServer server(80); void setup() { Serial.begin(9600); delay(10); // 连接无线网络 Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // 启动TCP服务器 server.begin(); Serial.println("Server started"); } void loop() { // 等待客户端连接 WiFiClient client = server.available(); if (!client) { return; } // 读取客户端发送的数据 Serial.println("New client"); while (client.connected()) { if (client.available()) { String request = client.readStringUntil('\r'); Serial.println(request); // 发送响应数据 client.println("Hello from server"); break; } } // 关闭连接 client.stop(); Serial.println("Client disconnected"); } ``` TCP客户端端代码: ``` #include <ESP8266WiFi.h> const char* ssid = "YourWiFiSSID"; const char* password = "YourWiFiPassword"; const char* serverIp = "192.168.1.100"; // TCP服务器的IP地址 int serverPort = 80; // TCP服务器的端口号 void setup() { Serial.begin(9600); delay(10); // 连接无线网络 Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); } void loop() { // 连接TCP服务WiFiClient client; if (!client.connect(serverIp, serverPort)) { Serial.println("Connection failed"); return; } // 发送数据到TCP服务client.println("Hello from client"); // 读取TCP服务器响应的数据 while (client.connected()) { if (client.available()) { String response = client.readStringUntil('\r'); Serial.println(response); break; } } // 关闭连接 client.stop(); Serial.println("Disconnected"); // 等待一段时间后再次连接 delay(5000); } ``` 在实际使用中,需要根据实际需求进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

闰土小蒋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值