1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-04-22 21:23:07 +03:00
Junxiao Shi d17ffc2874 WiFi: improve WiFiClient(Basic) examples (#5197)
WiFiClient no longer depends on now-defunct data.sparkfun.com
service, but uses a TCP "quote of the day" service instead.

fixes #4088
2018-10-11 02:08:13 -03:00

75 lines
1.6 KiB
C++

/*
This sketch sends a string to a TCP server, and prints a one-line response.
You must run a TCP server in your local network.
For example, on Linux you can use this command: nc -v -l 3000
*/
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "192.168.1.1";
const uint16_t port = 3000;
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
Serial.println();
Serial.println();
Serial.print("Wait for WiFi... ");
while (WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop() {
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
Serial.println("wait 5 sec...");
delay(5000);
return;
}
// This will send the request to the server
client.println("hello from ESP8266");
//read back one line from server
Serial.println("receiving from remote server");
String line = client.readStringUntil('\r');
Serial.println(line);
Serial.println("closing connection");
client.stop();
Serial.println("wait 5 sec...");
delay(5000);
}