Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Created September 30, 2010 01:36
Show Gist options
  • Save mitsuji/603879 to your computer and use it in GitHub Desktop.
Save mitsuji/603879 to your computer and use it in GitHub Desktop.
-module(flashpolicy).
-vsn("0.9.01").
-export([ start/0, stop/0 ]).
-export([ init/3 ]).
-export([ wait/2 ]).
-define(POLICY_FILE, "/path/to/policyfile.xml").
start() ->
start(?POLICY_FILE, 843, 3 ).
start( PolicyFile, Port, Num ) ->
Pid = create( PolicyFile, Port, Num ),
register(?MODULE, Pid).
stop() ->
stop( ?MODULE ).
create( PolicyFile, Port, Num ) ->
spawn(?MODULE, init, [ PolicyFile, Port, Num ]).
stop( Pid ) ->
Pid ! stop.
init( PolicyFile, Port, Num ) ->
case gen_tcp:listen(Port,[{active, false},{packet,0}]) of
{ok, Socket} ->
init_wait(Num, Socket, PolicyFile),
loop(Socket);
{error, Reason} ->
{error, Reason}
end.
loop(Socket) ->
receive
stop ->
gen_tcp:close(Socket);
_Other ->
loop(Socket)
end.
init_wait(0, _, _) ->
ok;
init_wait(Num, Socket, PolicyFile) ->
spawn(?MODULE, wait, [Socket, PolicyFile]),
init_wait(Num-1, Socket, PolicyFile).
wait(Socket, PolicyFile) ->
case gen_tcp:accept(Socket) of
{ok, ClientSocket} ->
spawn(?MODULE, wait, [Socket, PolicyFile]),
response( ClientSocket, PolicyFile);
Other ->
io:format("accept ~w returned ~w, bye.~n",[self(), Other]),
ok
end.
response( Socket, PolicyFile ) ->
inet:setopts(Socket,[{active,once}]),
receive
{ tcp, Socket, _ } ->
{ok, Policy} = file:read_file( PolicyFile ),
gen_tcp:send(Socket, Policy),
gen_tcp:shutdown(Socket, read_write );
{ tcp_closed, Socket } ->
io:format("client socket ~w closed.~n",[Socket]),
ok
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment