version: 0.1.0
+ ws server at "/" and port 11000 + simple ws handler casting to wsbus
This commit is contained in:
parent
454d1fb055
commit
052b0b25c7
6 changed files with 4777 additions and 0 deletions
16
src/wsio_app.erl
Normal file
16
src/wsio_app.erl
Normal file
|
@ -0,0 +1,16 @@
|
|||
-module(wsio_app).
|
||||
-behaviour(application).
|
||||
|
||||
-export([start/2]).
|
||||
-export([stop/1]).
|
||||
|
||||
start(_Type, _Args) ->
|
||||
Routes = [{"/", wsio_handler, none}],
|
||||
Dispatch = cowboy_router:compile([{'_', Routes}]),
|
||||
{ok, _} = cowboy:start_clear(httpd, [inet, {port, 11000}],
|
||||
#{env => #{dispatch => Dispatch}}
|
||||
),
|
||||
wsio_sup:start_link().
|
||||
|
||||
stop(_State) ->
|
||||
ok.
|
48
src/wsio_handler.erl
Normal file
48
src/wsio_handler.erl
Normal file
|
@ -0,0 +1,48 @@
|
|||
-module(wsio_handler).
|
||||
|
||||
-export([init/2]).
|
||||
-export([websocket_handle/2]).
|
||||
-export([websocket_init/1]).
|
||||
-export([websocket_info/2]).
|
||||
|
||||
-define(TTL_PING, 10000).
|
||||
|
||||
init(R, _) ->
|
||||
{cowboy_websocket, R, #{}}.
|
||||
|
||||
websocket_init(S) ->
|
||||
Ref = st:lookup(wsbus),
|
||||
{ok, S#{wsbus => nil, ref_wsbus => Ref}}.
|
||||
|
||||
websocket_handle({text, <<Data/binary>>}, S) ->
|
||||
case jsx:is_json(Data) of
|
||||
true ->
|
||||
websocket_handle({json, jsx:decode(Data)}, S);
|
||||
false ->
|
||||
{ok, S}
|
||||
end;
|
||||
websocket_handle({json, #{<<"ref">> := Ref}}, #{wsbus := nil} = S) ->
|
||||
{[{text, jsx:encode(#{<<"ref">> => Ref, <<"wsio-code">> => 0})}], S};
|
||||
websocket_handle({json, Data}, #{wsbus := BUS} = S) ->
|
||||
gen_server:cast(BUS, {call, Data, self()}),
|
||||
{ok, S};
|
||||
websocket_handle(_, State) ->
|
||||
{ok, State}.
|
||||
|
||||
websocket_info(close, S) ->
|
||||
{[close], S};
|
||||
websocket_info(ping, S) ->
|
||||
erlang:send_after(?TTL_PING, self(), ping),
|
||||
{[ping], S};
|
||||
websocket_info({send, #{} = Map}, S) ->
|
||||
{[{text, jsx:encode(Map)}], S};
|
||||
websocket_info({send, <<Bin/binary>>}, S) ->
|
||||
{[{text, Bin}], S};
|
||||
websocket_info({send, List}, S) when is_list(List) ->
|
||||
{List, S};
|
||||
websocket_info({_, {Ref, {error, notfound}}}, #{ref_wsbus := Ref} = S) ->
|
||||
{ok, S#{ref_wsbus => st:lookup(wsbus)}};
|
||||
websocket_info({_, {Ref, {ok, PID}}}, #{ref_wsbus := Ref} = S) ->
|
||||
{ok, maps:remove(ref_wsbus, S#{wsbus => PID})};
|
||||
websocket_info(_, S) ->
|
||||
{ok, S}.
|
12
src/wsio_sup.erl
Normal file
12
src/wsio_sup.erl
Normal file
|
@ -0,0 +1,12 @@
|
|||
-module(wsio_sup).
|
||||
-behaviour(supervisor).
|
||||
|
||||
-export([start_link/0]).
|
||||
-export([init/1]).
|
||||
|
||||
start_link() ->
|
||||
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
|
||||
|
||||
init([]) ->
|
||||
Procs = [],
|
||||
{ok, {{one_for_one, 1, 5}, Procs}}.
|
Loading…
Add table
Add a link
Reference in a new issue