Esp8266-Client.ino 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Esp8266 Websockets Client
  3. This sketch:
  4. 1. Connects to a WiFi network
  5. 2. Connects to a Websockets server
  6. 3. Sends the websockets server a message ("Hello Server")
  7. 4. Prints all incoming messages while the connection is open
  8. Hardware:
  9. For this sketch you only need an ESP8266 board.
  10. Created 15/02/2019
  11. By Gil Maimon
  12. https://github.com/gilmaimon/ArduinoWebsockets
  13. */
  14. #include <ArduinoWebsockets.h>
  15. #include <ESP8266WiFi.h>
  16. const char* ssid = "ssid"; //Enter SSID
  17. const char* password = "password"; //Enter Password
  18. const char* websockets_server_host = "serverip_or_name"; //Enter server adress
  19. const uint16_t websockets_server_port = 8080; // Enter server port
  20. using namespace websockets;
  21. WebsocketsClient client;
  22. void setup() {
  23. Serial.begin(115200);
  24. // Connect to wifi
  25. WiFi.begin(ssid, password);
  26. // Wait some time to connect to wifi
  27. for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
  28. Serial.print(".");
  29. delay(1000);
  30. }
  31. // Check if connected to wifi
  32. if(WiFi.status() != WL_CONNECTED) {
  33. Serial.println("No Wifi!");
  34. return;
  35. }
  36. Serial.println("Connected to Wifi, Connecting to server.");
  37. // try to connect to Websockets server
  38. bool connected = client.connect(websockets_server_host, websockets_server_port, "/");
  39. if(connected) {
  40. Serial.println("Connecetd!");
  41. client.send("Hello Server");
  42. } else {
  43. Serial.println("Not Connected!");
  44. }
  45. // run callback when messages are received
  46. client.onMessage([&](WebsocketsMessage message) {
  47. Serial.print("Got Message: ");
  48. Serial.println(message.data());
  49. });
  50. }
  51. void loop() {
  52. // let the websockets client check for incoming messages
  53. if(client.available()) {
  54. client.poll();
  55. }
  56. delay(500);
  57. }