Search code examples
socketstcperlangerlang-otpgen-tcp

gen_tcp:recv/2 returns error, einval


I have a client that creates N processes and all connecting to a server like this:

 send(State = #state{low = Low, high = Low}) ->
 NewState = receive_sockets(0, Low, State),
 NewState;
 send(State = #state{low = Low}) ->
   N = Low rem 10,
   Dest = lists:nth(N + 1, State#state.dest),
   spawn(?MODULE, loop, [self(), Dest, Low]),
   NewState = State#state{low = Low + 1},
   send(NewState).

 loop(From, {IP, Port}, Low) ->
   case gen_tcp:connect(IP, Port, [binary]) of
    {ok, Socket} ->
    gen_tcp:send(Socket, integer_to_binary(Low)),
    From ! {Low, Socket},
    loop1(Socket);
    %%timer:sleep(infinity);
   _Else ->
    io:format("The connection failed ~n"),
    loop(From, {IP, Port}, Low)
   end.

 loop1(Socket) ->
  case gen_tcp:recv(Socket, 0) of
   {ok, Data} ->
    io:format("Received ~n ~p", [Data]),
    loop1(Socket);
   {error, einval} ->
    io:format("error ~n")
 end.

I am creating many client connections. At sometime later, the server might send me some data, so I am waiting on that using gen_tcp:recv/2 but I get {error, einval}.

Also, is there any issue how I am using the sockets since I am observing that the sockets are being closed as soon as they are accepted.

Any inputs as to why?

Thanks


Solution

  • Default gen_tcp:connect use active mode, unless {active, false} is specified in the option list for the socket, in which case packets are retrieved by calling recv/2. Use {active, false} if you really want use gen_tcp:recv to handle the data. Please double check man pages of "gen_tcp" especially active mode relative.