| 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 |
|
| 6 |
-module(long_polling_h). |
| 7 |
|
| 8 |
-export([init/2]). |
| 9 |
-export([info/3]). |
| 10 |
-export([terminate/3]). |
| 11 |
|
| 12 |
init(Req, _) -> |
| 13 |
erlang:send_after(200, self(), timeout), |
| 14 |
{cowboy_loop, Req, 2, hibernate}. |
| 15 |
|
| 16 |
info(timeout, Req, 0) -> |
| 17 |
%% Send an unused status code to make sure there's no |
| 18 |
%% conflict with whatever Cowboy may send itself. |
| 19 |
{stop, cowboy_req:reply(<<"299 OK!">>, Req), 0}; |
| 20 |
info(timeout, Req, Count) -> |
| 21 |
erlang:send_after(200, self(), timeout), |
| 22 |
{ok, Req, Count - 1, hibernate}. |
| 23 |
|
| 24 |
terminate(stop, _, 0) -> |
| 25 |
ok; |
| 26 |
terminate({error, overflow}, _, _) -> |
| 27 |
ok. |