echo.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. echo.c - WebSockets echo server
  3. */
  4. #include "esp.h"
  5. /*
  6. Event callback. Invoked for incoming web socket messages and other events of interest.
  7. */
  8. static void echo_callback(HttpStream *stream, int event, int arg)
  9. {
  10. HttpPacket *packet;
  11. if (event == HTTP_EVENT_READABLE) {
  12. /*
  13. Grab the packet off the read queue.
  14. */
  15. packet = httpGetPacket(stream->readq);
  16. if (packet->type == WS_MSG_TEXT || packet->type == WS_MSG_BINARY) {
  17. /*
  18. Echo back the contents
  19. */
  20. httpSendBlock(stream, packet->type, httpGetPacketStart(packet), httpGetPacketLength(packet), 0);
  21. }
  22. } else if (event == HTTP_EVENT_APP_CLOSE) {
  23. mprLog("info echo", 0, "close event. Status status %d, orderly closed %d, reason %s", arg,
  24. httpWebSocketOrderlyClosed(stream), httpGetWebSocketCloseReason(stream));
  25. } else if (event == HTTP_EVENT_ERROR) {
  26. mprLog("info echo", 0, "error event");
  27. } else if (event == HTTP_EVENT_DESTROY) {
  28. mprLog("info echo", 0, "client disconnected");
  29. }
  30. }
  31. /*
  32. Action to run in response to the "test/echo" URI
  33. */
  34. static void echo_action() {
  35. /*
  36. Don't automatically finalize (complete) the request when this routine returns. This keeps the connection open.
  37. */
  38. dontAutoFinalize();
  39. /*
  40. Establish the event callback
  41. */
  42. espSetNotifier(getConn(), echo_callback);
  43. }
  44. /*
  45. Initialize the "echo" loadable module
  46. The default ESP name for a controller is "app" if there is no esp.json to define the app name.
  47. */
  48. ESP_EXPORT int esp_controller_app_echo(HttpRoute *route, MprModule *module) {
  49. /*
  50. Define the "echo" action that will run when the "test/echo" URI is invoked
  51. */
  52. espDefineAction(route, "test/echo", echo_action);
  53. return 0;
  54. }