ESP8266 创建TCP连接

发布于:2024-08-15 ⋅ 阅读:(130) ⋅ 点赞:(0)

TCP Client

使用WiFiClient类可以实现TCP Client

基本方法

  • 连接Server,connect
WiFiClient client;
client.connect(host, port)
  • 检测客户端是否存在数据流
client.available()
  • 读取客户端的一个字符
client.read();
  • 检查连接状态
client.connected()

使用网络串口工具,创建一个tcp server供该设备进行连接,可实现每十秒向服务端发送字符串"Hello from Arduino!",并且能够接受服务端发送的字符串并显示到串口

缺点:如果发送的间隔过短,可能出现同时输出两次字符串的情况

示例代码

#include <ESP8266WiFi.h>
#include <WiFiClient.h>

const char* ssid = "TP-LINK_3DF2";           // 替换为你的WiFi网络名称
const char* password = "123454321";          // 替换为你的WiFi网络密码
const char* host = "192.168.0.111";          // 替换为你的服务器地址
const uint16_t port = 8266;                  // 服务器端口号

WiFiClient client;
unsigned long previousMillis = 0;
const long interval = 10000;                 // 发送间隔时间为10秒

void setup() {
  Serial.begin(115200);

  // 连接到WiFi网络
  Serial.println("Connecting to WiFi...");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting...");
  }

  Serial.println("Connected to WiFi!");

  // 连接到服务器
  if (!client.connect(host, port)) {
    Serial.println("Connection failed.");
    return;
  }

  Serial.println("Connected to server!");
}

void loop() {
  // 实时接收服务器发送的数据
  String tmpStr = "";
  while (client.available()) {
    char c = client.read();
    tmpStr.concat(c); 
  }

  if(tmpStr.length() > 0){
    Serial.println(tmpStr);
    tmpStr = "";
  }
  
  // 获取当前时间
  unsigned long currentMillis = millis();

  // 检查是否已经过去了指定的间隔时间
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    // 发送数据到服务器
    sendDataToServer();
  }

  // 只在发送或接收失败时检查连接状态
  if (!client.connected()) {
    reconnectToServer();
  }
}

void sendDataToServer() {
  String message = "Hello from Arduino!";
  if (client.connected()) {
    client.println(message);
    Serial.print("Sent to server: ");
    Serial.println(message);
  } else {
    Serial.println("Failed to send, not connected to server.");
  }
}

void reconnectToServer() {
  Serial.println("Disconnected from server.");
  client.stop();

  // 尝试重新连接
  if (!client.connect(host, port)) {
    Serial.println("Reconnection failed.");
    delay(5000);  // 等待5秒后再尝试重新连接
  } else {
    Serial.println("Reconnected to server!");
  }
}

TCP Server


网站公告

今日签到

点亮在社区的每一天
去签到