SimpleWebSocket.ino 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Simple WebSocket client for ArduinoHttpClient library
  3. Connects to the WebSocket server, and sends a hello
  4. message every 5 seconds
  5. note: WiFi SSID and password are stored in config.h file.
  6. If it is not present, add a new tab, call it "config.h"
  7. and add the following variables:
  8. char ssid[] = "ssid"; // your network SSID (name)
  9. char pass[] = "password"; // your network password
  10. created 28 Jun 2016
  11. by Sandeep Mistry
  12. this example is in the public domain
  13. */
  14. #include <ArduinoHttpClient.h>
  15. #include <WiFi101.h>
  16. #include "config.h"
  17. char serverAddress[] = "echo.websocket.org"; // server address
  18. int port = 80;
  19. WiFiClient wifi;
  20. WebSocketClient client = WebSocketClient(wifi, serverAddress, port);
  21. int status = WL_IDLE_STATUS;
  22. int count = 0;
  23. void setup() {
  24. Serial.begin(9600);
  25. while ( status != WL_CONNECTED) {
  26. Serial.print("Attempting to connect to Network named: ");
  27. Serial.println(ssid); // print the network name (SSID);
  28. // Connect to WPA/WPA2 network:
  29. status = WiFi.begin(ssid, pass);
  30. }
  31. // print the SSID of the network you're attached to:
  32. Serial.print("SSID: ");
  33. Serial.println(WiFi.SSID());
  34. // print your WiFi shield's IP address:
  35. IPAddress ip = WiFi.localIP();
  36. Serial.print("IP Address: ");
  37. Serial.println(ip);
  38. }
  39. void loop() {
  40. Serial.println("starting WebSocket client");
  41. client.begin();
  42. while (client.connected()) {
  43. Serial.print("Sending hello ");
  44. Serial.println(count);
  45. // send a hello #
  46. client.beginMessage(TYPE_TEXT);
  47. client.print("hello ");
  48. client.print(count);
  49. client.endMessage();
  50. // increment count for next message
  51. count++;
  52. // check if a message is available to be received
  53. int messageSize = client.parseMessage();
  54. if (messageSize > 0) {
  55. Serial.println("Received a message:");
  56. Serial.println(client.readString());
  57. }
  58. // wait 5 seconds
  59. delay(5000);
  60. }
  61. Serial.println("disconnected");
  62. }