Advertisement
rs3hc

tcp arduino

Nov 28th, 2021
757
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. /*
  2.  *  This sketch sends a message to a TCP server
  3.  *
  4.  */
  5.  
  6. #include <WiFi.h>
  7. #include <WiFiMulti.h>
  8.  
  9. WiFiMulti WiFiMulti;
  10. IPAddress server;
  11. String str_hostname = "BatLOG_" + String(random(1,2000));
  12.  
  13. void setup()
  14. {
  15.     Serial.begin(115200);
  16.     delay(10);
  17.     // We start by connecting to a WiFi network
  18.     WiFiMulti.addAP("Batlog", "12345678");
  19.  
  20.     Serial.println();
  21.     Serial.println();
  22.     Serial.println("Waiting for WiFi... ");
  23.  
  24.     while(WiFiMulti.run() != WL_CONNECTED) {
  25.         Serial.print(".");
  26.         delay(500);
  27.     }
  28.     Serial.print("Hostname: ");
  29.     Serial.println(str_hostname);
  30.     Serial.println("");
  31.     Serial.println("WiFi connected");
  32.     Serial.println("IP address: ");
  33.     Serial.println(WiFi.localIP());
  34.     Serial.println("Server address: ");
  35.     Serial.println(WiFi.gatewayIP());
  36.     server = WiFi.gatewayIP();
  37.     Serial.println("");
  38.     Serial.println("");
  39.     Serial.println("");
  40.     Serial.println("Starting Loop....");
  41.     Serial.println("");
  42.     Serial.println("");
  43.        
  44.     delay(500);
  45. }
  46.  
  47.  
  48. void loop()
  49. {
  50.     const uint16_t port = 2000;
  51. //    const char * host = "192.168.1.10"; // ip or dns
  52.     IPAddress host = WiFi.gatewayIP(); // ip or dns
  53.    
  54.     Serial.print("Connecting to ");
  55.     Serial.println(host);
  56.  
  57.     // Use WiFiClient class to create TCP connections
  58.     WiFiClient client;
  59.  
  60.     if (!client.connect(host, port)) {
  61.         Serial.println("Connection failed.");
  62.         Serial.println("Waiting 5 seconds before retrying...");
  63.         delay(5000);
  64.         return;
  65.     }
  66.  
  67.     // This will send a request to the server
  68.     //uncomment this line to send an arbitrary string to the server
  69.     //client.print("Send this data to the server");
  70.     //uncomment this line to send a basic document request to the server
  71.     client.print(random(1,2000));
  72.  
  73.     //Serial.println("Closing connection.");
  74.    // client.stop();
  75.  
  76.     Serial.println("Waiting 5 seconds before restarting...");
  77.     delay(2000);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement