0
|
1 -module(aweconn).
|
|
2 -behavior(gen_server).
|
|
3
|
|
4 -export([start/1, init/1, handle_call/3, handle_cast/2, handle_info/2]).
|
|
5
|
|
6 start(Socket) ->
|
|
7 {ok, Pid} = gen_server:start(?MODULE, [], []),
|
|
8 set_socket(Pid, Socket).
|
|
9
|
|
10 set_socket(Pid, Socket) ->
|
|
11 ok = gen_tcp:controlling_process(Socket, Pid),
|
|
12 gen_server:cast(Pid, {set_socket, Socket}).
|
|
13
|
|
14 init(_Args) ->
|
|
15 io:format("aweconn starting~n"),
|
|
16 {ok, no_sock}.
|
|
17
|
|
18 handle_call(_Msg, _From, State) ->
|
|
19 {noreply, State}.
|
|
20
|
|
21 handle_cast({set_socket, NewSocket}, Socket) ->
|
|
22 io:format("aweconn got socket~n"),
|
|
23 inet:setopts(NewSocket, [{active, true}]),
|
|
24 State = case Socket of
|
|
25 no_sock -> NewSocket;
|
|
26 Old -> gen_tcp:close(Old), NewSocket
|
|
27 end,
|
|
28 {noreply, State};
|
|
29
|
|
30 handle_cast(_, State) ->
|
|
31 {noreply, State}.
|
|
32
|
|
33 handle_info({tcp, Socket, Data}, State) ->
|
|
34 io:format("Received: ~p~n", [Data]),
|
|
35 gen_tcp:send(Socket, Data),
|
|
36 {noreply, State};
|
|
37 handle_info(_Msg, State) ->
|
|
38 {noreply, State}.
|
|
39
|