forked from sockjs/sockjs-erlang
/
misultin_echo.erl
executable file
·50 lines (40 loc) · 1.45 KB
/
misultin_echo.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env escript
%%! -smp disable +A1 +K true -pz ./ebin -pa deps/misultin/ebin -input
-module(misultin_echo).
-mode(compile).
-export([main/1]).
main(_) ->
Port = 8081,
application:start(sockjs),
SockjsState = sockjs_handler:init_state(
<<"/echo">>, fun service_echo/2, []),
io:format(" [*] Running at http://localhost:~p~n", [Port]),
misultin:start_link(
[{port, Port},
{autoexit, false},
{ws_autoexit, false},
{loop, fun (Req) -> handle_http(Req, SockjsState) end},
{ws_loop, fun (Req) -> handle_ws(Req, SockjsState) end}]),
receive
_ -> ok
end.
%% --------------------------------------------------------------------------
handle_http(Req, SockjsState) ->
case Req:resource([]) of
["echo" | _T] ->
sockjs_handler:handle_req(SockjsState, {misultin, Req});
_Any ->
{ok, Data} = file:read_file("./examples/echo.html"),
Req:respond(200, [{"Content-Type", "text/html"}], Data)
end.
handle_ws(Req, SockjsState) ->
case string:tokens(Req:get(path), "/") of
["echo" | _T] ->
sockjs_misultin_handler:handle_ws(SockjsState, Req);
false ->
%% abort any other ws request
closed
end.
%% --------------------------------------------------------------------------
service_echo(Conn, {recv, Data}) -> sockjs:send(Data, Conn);
service_echo(_Conn, _) -> ok.