Reputation: 526
How to set receive timeout for socket, i could not find it in the socket option man.
my first soluation to the problem is to put after statement.
{ok, Listen} = gen_tcp:listen(Port, [..,{active, once}...]),
{ok, Socket} = gen_tcp:accept(Listen),
loop(Socket).
loop(Socket) ->
receive
{tcp, Socket, Data} ->
inet:setopts(Sock, [{active, once}]),
loop(Socket);
{tcp_closed, Socket} -> closed;
Other -> process_data(Other)
after 1000 -> time_out
end.
but the socket may never timeout because there are messages from other processes how can i set timeout without spawning other process ?
Upvotes: 7
Views: 2078
Reputation: 526
also you can use prim_inet:async_recv/3 which allow you to receive tcp message with timeout while receving other messages from different processes
read(Socket) ->
prim_inet:async_recv(Socket, 0, 1000),
receive
{inet_async, _ ,_ ,{ok, Msg}} ->
io:format("message received ~p~n",[Msg]),
read(Socket);
{inet_async,_,_,{error,timeout}} ->
io:format("timeout !"),
catch gen_tcp:close(Socket);
{fake, Msg} -> io:format("Message = ~p~n", [Msg]),
read(Socket)
end.
Upvotes: 0
Reputation: 376
You can't specify a receive timeout if you are using active mode. If you need to control receive timeout behavior, switch to passive mode on the socket, i.e. {active,false}
on the socket options, and then use gen_tcp:recv
with a receive timeout option.
In addition, a lot of Erlang socket server designs use an Erlang process per client connection. You can see http://www.trapexit.org/Building_a_Non-blocking_TCP_server_using_OTP_principles and http://20bits.com/article/erlang-a-generalized-tcp-server for examples. The OTP provides a lot of great ways to build robust servers with Erlang; take advantage of it!
Upvotes: 8