long_polling_h.erl 782 B

123456789101112131415161718192021222324252627
  1. %% This module implements a loop handler for long-polling.
  2. %% It starts by sending itself a message after 200ms,
  3. %% then sends another after that for a total of 3 messages.
  4. %% When it receives the last message, it sends a 102 reply back.
  5. -module(long_polling_h).
  6. -export([init/2]).
  7. -export([info/3]).
  8. -export([terminate/3]).
  9. init(Req, _) ->
  10. erlang:send_after(200, self(), timeout),
  11. {cowboy_loop, Req, 2, hibernate}.
  12. info(timeout, Req, 0) ->
  13. %% Send an unused status code to make sure there's no
  14. %% conflict with whatever Cowboy may send itself.
  15. {stop, cowboy_req:reply(<<"299 OK!">>, Req), 0};
  16. info(timeout, Req, Count) ->
  17. erlang:send_after(200, self(), timeout),
  18. {ok, Req, Count - 1, hibernate}.
  19. terminate(stop, _, 0) ->
  20. ok;
  21. terminate({error, overflow}, _, _) ->
  22. ok.