I have a tcp server and a client. The client spawns 1000 processes each trying to connect to the tcp server. I can see that the tcp server is accepting 245 connections and rejecting all the rest. Every time, the server is accepting the first 245.
Fixes:
Tried to increase the backlog attribute but did not work.
Tried to call timer:sleep(N) after each process spawn so that I can reduce the rate at which tcp server can accept clients. Failed!
Server and client:
accept(LSocket) ->
case gen_tcp:accept(LSocket) of
{ok, Socket} ->
io:format("Accepted ~n"),
{sockets, List} = hd(ets:lookup(csockets, sockets)),
NewList = [Socket | List],
ets:insert(csockets, {sockets, NewList}),
Pid = spawn(fun() ->
loop(Socket, 0)
end),
gen_tcp:controlling_process(Socket, Pid),
accept(LSocket);
{error, closed} ->
error
end.
Client:
send(State = #state{low = Low, high = Low}) ->
NewState = receive_sockets(0, Low, State),
NewState;
send(State = #state{low = Low}) ->
N = Low rem 2,
Dest = lists:nth(2, State#state.dest),
loop(self(), Dest, Low),
NewState = State#state{low = Low + 1},
send(NewState).
loop(From, {IP, Port}, Low) ->
case gen_tcp:connect(IP, Port, []) of
{ok, Socket} ->
gen_tcp:send(Socket, integer_to_binary(Low)),
From ! {Low, Socket},
Pid = spawn(?MODULE, receive_from_other_users, []),
gen_tcp:controlling_process(Socket, Pid);
_Else ->
io:format("The connection failed ~n"),
loop(From, {IP, Port}, Low)
end.