ref: rc/2.0.0 utos/utos/src/utos_net_websocket.erl -rw-r--r-- 2.1 KiB View raw
                                                                                
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
-module(utos_net_websocket).
-behaviour(gen_server).

-export([start_link/1]).

-export(
   [
    code_change/3,
    handle_call/3,
    handle_cast/2,
    handle_info/2,
    init/1,
    terminate/2
   ]
  ).

-export(
   [
    state/1
   ]
  ).

-define(SECKEY, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").
-define(SERVER, ?MODULE).
-define(TCP_OPTIONS, [
		      binary,
		      {active, true},
		      {nodelay, true},
		      {packet, raw},
		      {reuseaddr, true},
		      {send_timeout_close, true}
		     ]).

call(To, Msg) ->
    gen_server:call(To, Msg).

cast(To, Msg) ->
    gen_server:cast(To, Msg).

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

handle_call(state, _, S) ->
    {reply, {ok, S}, S};
handle_call(_Request, _From, State) ->
    {reply, ok, State}.

handle_cast({net, closed, {tcp, Socket}}, S) ->
    {ok, Handler} = utos_net_websocket_state:handler_get(Socket, S),
    {ok, State} = utos_net_websocket_state:handler_del(Socket, S),
    cast(Handler, {net, closed, websocket}),
    {noreply, State};
handle_cast({net, init, {tcp, Socket}}, #{<<"bus">> := Bus} = S) ->
    {ok, Handler} = utos_net_websocket_handler:start_link(Socket, Bus),
    {ok, State} = utos_net_websocket_state:handler_add({Socket, Handler}, S),
    {noreply, State};
handle_cast({net, input, {tcp, Socket}, Payload}, S) ->
    {ok, Handler} = utos_net_websocket_state:handler_get(Socket, S),
    cast(Handler, {net, input, websocket, Payload}),
    {noreply, S};
handle_cast(_Msg, State) ->
    io:format("OUT! -> ~p~n", [_Msg]),
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

init({Name, Port, Bus, Options}) ->
    process_flag(trap_exit, true),
    {ok, TCP} = utos_net_tcp:open(self(), Port, Options),
    State = #{
      <<"bus">> => Bus,
      <<"handlers">> => #{},
      <<"name">> => Name,
      <<"port">> => Port,
      <<"tcp">> => TCP
     },
    {ok, State}.

start_link({Name, Port, Bus}) ->
    start_link({Name, Port, Bus, ?TCP_OPTIONS});
start_link({Name, Port, Bus, Options}) ->
    gen_server:start_link({local, Name}, ?MODULE, {Name, Port, Bus, Options}, []).

state(Pid) ->
    call(Pid, state).

terminate(_Reason, _State) ->
    ok.