Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 70 lines (61 sloc) 2.251 kb
c4fd143 @vinoski add support for W3C Server-Sent Events
vinoski authored
1 %%%----------------------------------------------------------------------
2 %%% File : yaws_sse.erl
3 %%% Author : Steve Vinoski <vinoski@ieee.org>
4 %%% Purpose : Support for Server-Sent Events
5 %%% Created : 31 May 2012 by Steve Vinoski <vinoski@ieee.org>
6 %%%----------------------------------------------------------------------
7 -module(yaws_sse).
8 -author('vinoski@ieee.org').
9
10 -export([headers/1,
11 event/0, event/1,
12 data/0, data/1, data/2,
13 id/0, id/1,
14 retry/0, retry/1,
15 comment/1,
16 send_events/2, send_events/3
17 ]).
18
19 headers(StreamPid) ->
20 [{status, 200},
21 {header, {"Cache-Control", "no-cache"}},
22 {header, {"Connection", "Keep-Alive"}},
23 {header, {transfer_encoding, erase}},
24 {streamcontent_from_pid, "text/event-stream", StreamPid}].
25
26 event() ->
27 <<"event\n">>.
28 event(EventName) ->
29 [<<"event:">>, EventName, <<"\n">>].
30
31 data() ->
32 <<"data\n">>.
33 data(Data) ->
34 [<<"data:">>, Data, <<"\n">>].
35 %% The version below trims out all embedded newlines. If you send data
36 %% containing newlines using the version above, your events will be
37 %% misinterpreted at the client. If the result of trimming includes
38 %% any empty strings or binaries, they are dropped and not sent.
39 data(Data0, [trim]) ->
40 Bin = iolist_to_binary(Data0),
41 Tokens = case catch binary:split(Bin, <<"\n">>, [global, trim]) of
42 {'EXIT', {undef, [{binary,split,__}|_]}} ->
43 %% handle older releases of Erlang
44 Lst = binary_to_list(Bin),
45 [Tok || Tok <- string:tokens(Lst, "\n")];
46 Bins ->
47 [B || B <- Bins, B /= <<>>]
48 end,
49 [data(Data) || Data <- Tokens].
50
51 id() ->
52 <<"id\n">>.
53 id(Id) when is_integer(Id) ->
54 [<<"id:">>, integer_to_list(Id), <<"\n">>];
55 id(Id) ->
56 [<<"id:">>, Id, <<"\n">>].
57
58 retry() ->
59 <<"retry\n">>.
60 retry(ReconnectionTime) ->
61 [<<"retry:">>, integer_to_list(ReconnectionTime), <<"\n">>].
62
63 comment(Comment) ->
64 [<<":">>, Comment, <<"\n">>].
65
66 send_events(Socket, Events) ->
67 send_events(Socket, Events, fun yaws_api:stream_process_deliver/2).
68 send_events(Socket, Events, SendFun) ->
69 SendFun(Socket, [Events, <<"\n">>]).
Something went wrong with that request. Please try again.