Skip to content

Instantly share code, notes, and snippets.

@xjia1
Last active December 10, 2015 12:38
Show Gist options
  • Save xjia1/4434980 to your computer and use it in GitHub Desktop.
Save xjia1/4434980 to your computer and use it in GitHub Desktop.
-module(etalk).
-export[start/2, acceptor/1].
start(Port, NumWorkers) ->
Opts = [binary, {active, false}],
case gen_tcp:listen(Port, Opts) of
{ok, ListenSock} ->
start_acceptors(NumWorkers, ListenSock),
inet:port(ListenSock)
; {error, Reason} ->
{error, Reason}
end.
start_acceptors(0, _) -> ok;
start_acceptors(N, LS) ->
spawn(?MODULE, acceptor, [LS]),
start_acceptors(N-1, LS).
acceptor(LS) ->
case gen_tcp:accept(LS) of
{ok, S} ->
worker(S),
acceptor(LS)
; Other ->
io:format("accept returned ~w~n", [Other]),
ok
end.
worker(S) ->
gen_tcp:shutdown(S, read),
gen_tcp:send(S, <<"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nHello, world!\r\n">>),
gen_tcp:shutdown(S, write).
% Test with:
% httperf --hog --timeout=5 --client=0/1 --server=localhost --port=7777 --uri=/ --send-buffer=4096 --recv-buffer=16384 --num-conns=5000 --num-calls=10 --rate=100
-module(mini_server).
-export([start/1]).
start(Port) ->
{ok, LSock} = gen_tcp:listen(Port, [{active, false}]),
{ok, Sock} = gen_tcp:accept(LSock),
ok = gen_tcp:send(Sock, <<"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nHello, world!\r\n">>),
ok = gen_tcp:close(Sock),
ok = gen_tcp:close(LSock).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment