Erlang socket and receive timeout

erlang, sockets, timeout

Solution

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!

Problem

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 ?

Original source