long_polling_h.erl 715 B

1234567891011121314151617181920212223242526
  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, cowboy_req:reply(102, Req), 0};
  15. info(timeout, Req, Count) ->
  16. erlang:send_after(200, self(), timeout),
  17. {loop, Req, Count - 1, hibernate}.
  18. terminate({normal, shutdown}, _, 0) ->
  19. ok;
  20. terminate({error, overflow}, _, _) ->
  21. ok.