[英]ESP32: Send a simple TCP Message and receive the response
我想在我的計算機上使用 ESP32 執行與 .netcat“nc”命令相同的請求:
電腦:
$ nc tcpbin.com 4242
Test
Test
到目前為止我已經嘗試過:
#include <Arduino.h>
#include <WiFi.h>
WiFiClient localClient;
const char* ssid = "...";
const char* password = "...";
const uint port = 4242;
const char* ip = "45.79.112.203"; // tcpbin.com's ip
void setup() {
Serial.begin(115200);
Serial.println("Connect Wlan");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(WiFi.localIP());
}
void loop() {
sendRequest();
delay(200);
}
void sendRequest() {
if(!localClient.connected()) {
if (localClient.connect(ip, port)) {
Serial.println("localClient connected");
localClient.write('A'); //Single char
Serial.println("msg sent");
}
}
if(localClient.connected()) {
Serial.println("Start reading");
if (localClient.available() > 0) {
char c = localClient.read();
Serial.print(c);
}
Serial.println("Stop reading");
}
}
我很確定我在實施過程中誤解了 tcp 概念的某些內容。 但是,在嘗試了各種方法並嘗試了其他代碼片段之后,我無法想出解決方案。
先感謝您
問候萊昂
您的代碼有幾個問題。
如果您測試nc
,您會注意到在您按下“返回”之前服務器不會確認。 您在代碼中發送一個字節而沒有終止,因此服務器正在等待后續數據。 要終止數據,您需要發送 '\n',或者不使用client.write('A')
,而是使用client.println('A')
。
A.網絡響應需要時間,您當前的代碼期望立即響應而無需等待if (localClient.available() > 0)
。
這是將起作用的代碼:
void sendRequest() {
if (localClient.connect(ip, port)) { // Establish a connection
if (localClient.connected()) {
localClient.println('A'); // send data
Serial.println("[Tx] A");
}
while (!localClient.available()); // wait for response
String str = localClient.readStringUntil('\n'); // read entire response
Serial.print("[Rx] ");
Serial.println(str);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.