Minimal-Esp32-Client.ino 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Minimal Esp32 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. Sends the websocket server a "ping"
  8. 5. Prints all incoming messages while the connection is open
  9. NOTE:
  10. The sketch dosen't check or indicate about errors while connecting to
  11. WiFi or to the websockets server. For full example you might want
  12. to try the example named "Esp32-Client".
  13. Hardware:
  14. For this sketch you only need an ESP8266 board.
  15. Created 15/02/2019
  16. By Gil Maimon
  17. https://github.com/gilmaimon/ArduinoWebsockets
  18. */
  19. #include <ArduinoWebsockets.h>
  20. #include <WiFi.h>
  21. const char* ssid = "ssid"; //Enter SSID
  22. const char* password = "password"; //Enter Password
  23. const char* websockets_server_host = "serverip_or_name"; //Enter server adress
  24. const uint16_t websockets_server_port = 8080; // Enter server port
  25. using namespace websockets;
  26. void onMessageCallback(WebsocketsMessage message) {
  27. Serial.print("Got Message: ");
  28. Serial.println(message.data());
  29. }
  30. void onEventsCallback(WebsocketsEvent event, String data) {
  31. if(event == WebsocketsEvent::ConnectionOpened) {
  32. Serial.println("Connnection Opened");
  33. } else if(event == WebsocketsEvent::ConnectionClosed) {
  34. Serial.println("Connnection Closed");
  35. } else if(event == WebsocketsEvent::GotPing) {
  36. Serial.println("Got a Ping!");
  37. } else if(event == WebsocketsEvent::GotPong) {
  38. Serial.println("Got a Pong!");
  39. }
  40. }
  41. WebsocketsClient client;
  42. void setup() {
  43. Serial.begin(115200);
  44. // Connect to wifi
  45. WiFi.begin(ssid, password);
  46. // Wait some time to connect to wifi
  47. for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
  48. Serial.print(".");
  49. delay(1000);
  50. }
  51. // run callback when messages are received
  52. client.onMessage(onMessageCallback);
  53. // run callback when events are occuring
  54. client.onEvent(onEventsCallback);
  55. // Connect to server
  56. client.connect(websockets_server_host, websockets_server_port, "/");
  57. // Send a message
  58. client.send("Hello Server");
  59. // Send a ping
  60. client.ping();
  61. }
  62. void loop() {
  63. client.poll();
  64. }