TCP Client

使用WiFiClient类可以实现TCP Client

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

使用网络串口工具,创建一个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!");
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.

TCP Server