WebSocketServerFragmentation.ino 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * WebSocketServer.ino
  3. *
  4. * Created on: 22.05.2015
  5. *
  6. */
  7. #include <Arduino.h>
  8. #include <ESP8266WiFi.h>
  9. #include <ESP8266WiFiMulti.h>
  10. #include <WebSocketsServer.h>
  11. #include <Hash.h>
  12. ESP8266WiFiMulti WiFiMulti;
  13. WebSocketsServer webSocket = WebSocketsServer(81);
  14. #define USE_SERIAL Serial
  15. String fragmentBuffer = "";
  16. void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  17. switch(type) {
  18. case WStype_DISCONNECTED:
  19. USE_SERIAL.printf("[%u] Disconnected!\n", num);
  20. break;
  21. case WStype_CONNECTED: {
  22. IPAddress ip = webSocket.remoteIP(num);
  23. USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
  24. // send message to client
  25. webSocket.sendTXT(num, "Connected");
  26. }
  27. break;
  28. case WStype_TEXT:
  29. USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
  30. break;
  31. case WStype_BIN:
  32. USE_SERIAL.printf("[%u] get binary length: %u\n", num, length);
  33. hexdump(payload, length);
  34. break;
  35. // Fragmentation / continuation opcode handling
  36. // case WStype_FRAGMENT_BIN_START:
  37. case WStype_FRAGMENT_TEXT_START:
  38. fragmentBuffer = (char*)payload;
  39. USE_SERIAL.printf("[%u] get start start of Textfragment: %s\n", num, payload);
  40. break;
  41. case WStype_FRAGMENT:
  42. fragmentBuffer += (char*)payload;
  43. USE_SERIAL.printf("[%u] get Textfragment : %s\n", num, payload);
  44. break;
  45. case WStype_FRAGMENT_FIN:
  46. fragmentBuffer += (char*)payload;
  47. USE_SERIAL.printf("[%u] get end of Textfragment: %s\n", num, payload);
  48. USE_SERIAL.printf("[%u] full frame: %s\n", num, fragmentBuffer.c_str());
  49. break;
  50. }
  51. }
  52. void setup() {
  53. // USE_SERIAL.begin(921600);
  54. USE_SERIAL.begin(115200);
  55. //Serial.setDebugOutput(true);
  56. USE_SERIAL.setDebugOutput(true);
  57. USE_SERIAL.println();
  58. USE_SERIAL.println();
  59. USE_SERIAL.println();
  60. for(uint8_t t = 4; t > 0; t--) {
  61. USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
  62. USE_SERIAL.flush();
  63. delay(1000);
  64. }
  65. WiFiMulti.addAP("SSID", "passpasspass");
  66. while(WiFiMulti.run() != WL_CONNECTED) {
  67. delay(100);
  68. }
  69. webSocket.begin();
  70. webSocket.onEvent(webSocketEvent);
  71. }
  72. void loop() {
  73. webSocket.loop();
  74. }