NodeMcu arduino ESP8266WIFI 模块 例程 WIFIClienBasic(TCP服务器发送信息)

12 篇文章 9 订阅

NodeMcu arduino ESP8266WIFI 模块 WIFIClienBasic(TCP服务器发送信息)

流程

  1. 配置连接网络
  2. 发送TCP请求
  3. 获取接受数据打印
/*
    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);
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

闰土小蒋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值