Esp8266-Server.ino 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Minimal Esp8266 Websockets Server
  3. This sketch:
  4. 1. Connects to a WiFi network
  5. 2. Starts a websocket server on port 80
  6. 3. Waits for connections
  7. 4. Once a client connects, it wait for a message from the client
  8. 5. Sends an "echo" message to the client
  9. 6. closes the connection and goes back to step 3
  10. Hardware:
  11. For this sketch you only need an ESP8266 board.
  12. Created 15/02/2019
  13. By Gil Maimon
  14. https://github.com/gilmaimon/ArduinoWebsockets
  15. */
  16. #include <ArduinoWebsockets.h>
  17. #include <ESP8266WiFi.h>
  18. const char* ssid = "ssid"; //Enter SSID
  19. const char* password = "password"; //Enter Password
  20. using namespace websockets;
  21. WebsocketsServer server;
  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 < 15 && WiFi.status() != WL_CONNECTED; i++) {
  28. Serial.print(".");
  29. delay(1000);
  30. }
  31. Serial.println("");
  32. Serial.println("WiFi connected");
  33. Serial.println("IP address: ");
  34. Serial.println(WiFi.localIP()); //You can get IP address assigned to ESP
  35. server.listen(80);
  36. Serial.print("Is server live? ");
  37. Serial.println(server.available());
  38. }
  39. void loop() {
  40. WebsocketsClient client = server.accept();
  41. if(client.available()) {
  42. WebsocketsMessage msg = client.readBlocking();
  43. // log
  44. Serial.print("Got Message: ");
  45. Serial.println(msg.data());
  46. // return echo
  47. client.send("Echo: " + msg.data());
  48. // close the connection
  49. client.close();
  50. }
  51. delay(1000);
  52. }