Skip to content

Instantly share code, notes, and snippets.

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