/* Simple basic example From ESP32/ESP8266 as Client to Nodejs as a server via TCP Protocol. */ //----------- ESP32 as TCP Client---------------- // file .ino #include "WiFi.h" const char* ssid = "SSID"; const char* password = "password"; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void loop() { const uint16_t port = 52275; // port TCP server const char * host = "192.168.1.19"; // ip or dns Serial.print("Connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; if (!client.connect(host, port)) { Serial.println("Connection failed."); Serial.println("Waiting 5 seconds before retrying..."); delay(5000); return; } // This will send a request to the server //uncomment this line to send an arbitrary string to the server //client.print("Send this data to the server"); //uncomment this line to send a basic document request to the server client.print("hello server im from esp"); int maxloops = 0; //wait for the server's reply to become available while (!client.available() && maxloops < 1000) { maxloops++; delay(1); //delay 1 msec } if (client.available() > 0) { //read back one line from the server String line = client.readStringUntil('\r'); Serial.println(line); } else { Serial.println("client.available() timed out "); } Serial.println("Closing connection."); client.stop(); Serial.println("Waiting 5 seconds before restarting..."); delay(5000); } // ------------------- NodeJS TCP server ------------------------------ // file.js var net = require('net'); var textChunk = ''; var server = net.createServer(function(socket) { socket.write('callback server\r\n'); socket.on('data', function(data){ console.log(data); textChunk = data.toString('utf8'); console.log('from server'+textChunk); socket.write(textChunk); }); }); server.listen(52275, '0.0.0.0');