long_polling_h.erl 735 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. -behaviour(cowboy_loop_handler).
  7. -export([init/3]).
  8. -export([info/3]).
  9. -export([terminate/3]).
  10. init(_, Req, _) ->
  11. erlang:send_after(200, self(), timeout),
  12. {loop, Req, 2, 5000, hibernate}.
  13. info(timeout, Req, 0) ->
  14. {ok, Req2} = cowboy_req:reply(102, Req),
  15. {ok, Req2, 0};
  16. info(timeout, Req, Count) ->
  17. erlang:send_after(200, self(), timeout),
  18. {loop, Req, Count - 1, hibernate}.
  19. terminate({normal, shutdown}, _, 0) ->
  20. ok;
  21. terminate({error, overflow}, _, _) ->
  22. ok.