Skip to content

Instantly share code, notes, and snippets.

@msantos
Created July 25, 2015 14:17
Show Gist options
  • Save msantos/c9b6c459e10f44ab90c2 to your computer and use it in GitHub Desktop.
Save msantos/c9b6c459e10f44ab90c2 to your computer and use it in GitHub Desktop.
-module(xt).
-export([start/1,start/4]).
-export([connect/5]).
-define(RESPONSE_TIMEOUT, 20000).
-define(NUM_CLIENTS, 10).
-define(DELAY, 1000).
-define(NUM_REQUESTS, 100).
start(Port) ->
start(Port, ?NUM_CLIENTS, ?DELAY, ?NUM_REQUESTS).
start(Port, NumClients, Delay, NumRequests) ->
Packet = binary:copy(<<"x">>, 100),
[ spawn_link(?MODULE, connect, [Port, Client, Packet, Delay, NumRequests]) || Client <- lists:seq(1, NumClients) ].
connect(Port, Client, Packet, Delay, N) ->
timer:sleep(crypto:rand_uniform(1, 5 * 1000)), % stagger the requests (milliseconds)
error_logger:info_report([{connecting, Client, N}]),
{ok, Socket} = gen_tcp:connect({127,0,0,1}, Port, [binary]),
request(Client, Socket, Packet, Delay, N).
request(Client,_,_,_,0) ->
error_logger:info_report([{complete, {client,Client}}]),
run_complete;
request(Client, Socket, Packet, Delay, N) ->
Size = byte_size(Packet),
ok = gen_tcp:send(Socket, <<Size:4/unsigned-integer-unit:8, Packet/binary>>),
receive
{tcp, Socket, _Data} ->
timer:sleep(Delay),
request(Client, Socket, Packet, Delay, N-1);
Error ->
Error
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment