How to close TCP socket: ESP8266 NodeMCU v1.0(Amica) Arduino
Posted: Thu Apr 13, 2017 12:58 pm
I'm using netcat on linux to create a listening tcp server and testing an ESP wifi sketch in the Arduino IDE (1.6.9) that creates a client connection to the server, sends data, checks for any replies and then closes & sleeps. The trouble is that netcat doesn't think the connect has been closed and therefore does not accept a new connection the next time the ESP tries to connect. If I use hyperterminal, then netcat sees the closed TCP socket connection.
Any ideas?
Code: Select all
/*
* This sketch sends a message to a TCP server
* use netcat in linux
* for a single use connection:
* nc -1 1024
* for a continiously listening server
* while true; do nc -l 1024; done
*/
#include <ESP8266WiFi.h>
#include <Streaming.h>
//////////////////////
// WiFi Definitions //
//////////////////////
const char WiFiSSID[] = "basement";
const char WiFiPSK[] = "1234567890";
const uint16_t port = 1024;
const char * host = "192.168.12.251"; // ip or dns
const int SLEEP_DELAY_IN_SECONDS = 10;
void setup(){
Serial.begin(115200);
delay(100);
connectWifi();
send_Data();
sleep();
}
void loop() {
yield(); // should never reach the main loop, after it wakes from sleep, program starts from the beginning
}
void connectWifi(){
WiFi.mode(WIFI_STA);
WiFi.begin(WiFiSSID, WiFiPSK);
Serial.print("\r\n\nWaiting for WiFi to connect");
while(WiFi.status() != WL_CONNECTED) {
Serial.print("."); // print '.' every 0.5s while waiting for wifi to connect
delay(500);
}
Serial.print("\r\nWiFi connected");
Serial.print("\r\nIP address: ");
Serial.print(WiFi.localIP());
}
void send_Data(){
WiFiClient client;
Serial.print("\r\nConnecting to ");
Serial.print(host);
while (!client.connect(host, port)) {
Serial.print("\r\n connection failed");
Serial.print("\r\n waiting 1 sec...");
delay(1000);
}
// This will send the data to the server
client.print("\r\nHello from ");
client.print(ESP.getChipId());
client.print(", uptime(s) ");
client.print(millis()/1000);
//read back one line from server
//while (client.available()){ // client.available doesn't seem to detect any waiting data from netcat
String line = client.readStringUntil('\r');
Serial.print("\r\nreceived>");
Serial.print(line);
Serial.print("<");
//}
Serial.print("\r\nClient.status: ");
Serial.print(client.status()); // 4 when connection is open
Serial.print("\r\nclosing connection");
client.stop();
WiFi.disconnect();
delay(1000);
Serial.print("\r\nClient.status: ");
Serial.print(client.status()); // 0 when connection is closed, but netcat doesn't detect the close
}
void sleep(){
Serial << "\r\nEntering deep sleep mode for " << SLEEP_DELAY_IN_SECONDS << " seconds..." << endl;
ESP.deepSleep(SLEEP_DELAY_IN_SECONDS * 1000000, WAKE_RF_DEFAULT);
delay(500); // wait for deep sleep to happen}
}
Any ideas?