- Sat Apr 01, 2017 2:40 pm
#64487
I beleave that what you read in different threads is that you can not switch port on existing connections or on existing listening server, that's why we need to do close()/begin(). And also that the setPort() I've provided didn't exist yet in any releases.
Here is the testing sketch :
Code: Select all#include <ESP8266WiFi.h>
WiFiServer tcpserver(23); // Telnet Port
WiFiClient client;
uint current_port = 23;
void setup() {
int timeout = 60;
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin("Giroles-Salon", "PitchouFacePouding");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
timeout--;
if (timeout <= 0) {
Serial.printf("\r\nWiFi connect aborted !\r\n");
while(1) {};
}
}
String str = "\r\nWiFi connected !\r\nIP = ";
str += WiFi.localIP().toString();
Serial.println(str);
tcpserver.begin();
}
void loop() {
if (client) {
if (client.status() == CLOSED) {
client.stop();
Serial.println("connection closed !");
}
if (client.available()) {
client.setNoDelay(1);
String req = client.readStringUntil('\r');
client.flush();
if (req.equals("hello")) {
client.println("Hello from ESP8266 !");
}
else if (req.equals("switch")) {
tcpserver.close();
if (current_port == 23)
current_port = 24;
else
current_port = 23;
tcpserver.setPort(current_port);
tcpserver.begin();
}
else if (req.equals("exit")) {
client.stop();
}
else if (req.length() > 0)
client.println("Unknown command !");
else
client.print(">");
}
}
else {
client = tcpserver.available();
}
}
To execute, simply do "telnet <esp_ipaddr> 23", then type command "hello" just for test, and real "switch" command will switch port to 24, then type "exit". Trying again "telnet <esp_ipaddr> 23" will fail, but doing "telnet <esp_ipaddr> 24" will succeed. Doing "switch" again will bring it back to 23...