You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32实现类似netcat的TCP消息发送与响应接收

ESP32 模拟 Netcat(nc)双向TCP通信功能

需求说明

希望用ESP32实现与电脑端nc命令相同的功能,电脑端示例操作:

$ nc tcpbin.com 4242
Test
Test

当前问题分析

你的代码存在以下几个关键点问题:

  • 仅单次发送单个字符,未实现双向通信(无法从串口输入内容发送到服务器,也未持续读取服务器响应);
  • 读取服务器响应时仅读取单个字符,未处理完整的响应数据;
  • 循环逻辑设计不合理,频繁触发连接检查和读取操作,易导致通信异常。

修正后的代码

#include <Arduino.h>
#include <WiFi.h>

WiFiClient tcpClient;

// WiFi配置
const char* ssid = "你的WiFi名称";
const char* password = "你的WiFi密码";

// TCP服务器配置
const uint16_t serverPort = 4242;
const char* serverIp = "45.79.112.203"; // tcpbin.com的IP

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

  // 连接WiFi
  Serial.println("正在连接WiFi...");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi连接成功,本地IP:" + WiFi.localIP().toString());
}

void loop() {
  // 检查TCP连接,断开则重连
  if (!tcpClient.connected()) {
    reconnectToServer();
  }

  // 从串口读取输入,发送到TCP服务器
  if (Serial.available() > 0) {
    String inputMsg = Serial.readStringUntil('\n');
    // 加上换行符,模拟nc的回车发送行为
    inputMsg += "\n";
    if (tcpClient.connected()) {
      tcpClient.print(inputMsg);
      Serial.print("已发送:");
      Serial.print(inputMsg);
    }
  }

  // 从TCP服务器读取响应,输出到串口
  if (tcpClient.connected() && tcpClient.available() > 0) {
    String response = tcpClient.readStringUntil('\n');
    Serial.print("服务器响应:");
    Serial.println(response);
  }

  delay(10);
}

// 重连TCP服务器函数
void reconnectToServer() {
  Serial.println("\n正在连接TCP服务器...");
  tcpClient.stop(); // 关闭旧连接
  if (tcpClient.connect(serverIp, serverPort)) {
    Serial.println("TCP服务器连接成功!");
  } else {
    Serial.println("连接失败,5秒后重试...");
    delay(5000);
  }
}

关键改进点

  • 双向通信:同时监听串口输入和TCP服务器响应,实现和nc一致的交互逻辑;
  • 完整数据处理:使用readStringUntil('\n')读取整行数据,匹配tcpbin.com的echo服务换行触发逻辑;
  • 稳定重连机制:连接断开后自动尝试重连,避免频繁重试;
  • 符合nc行为:发送时添加换行符,模拟电脑端nc输入回车发送的操作。

内容的提问来源于stack exchange,提问作者Elchman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:35:28