gen_tcp:send with timeout

Matthias Lang matthias@REDACTED
Sun Feb 22 03:31:59 CET 2004

Eric Newhuis writes:
 > Is there a "standard" idiom for calling gen_tcp:send with a timeout?
 > I'd like to say gen_tcp:send(Socket, Data, Timeout) but there is no 
 > such (documented) function, my server is queueing, and my process is 
 > blocked forever.

Better late than never...

One way to do it using documented functions is to spawn a 'disposable'
process each time you want to send something, and supervise it with a
timer, e.g.

   Parent = self(),
   Ref = make_ref(),

   Disposable = fun() ->
      ok = gen_tcp:send(S, Bin),
      Parent ! Ref


      Ref -> ok
   after 5000 ->
     exit(timeout)  % or do something more complex

This is quite general, but it feels roundabout. There's a more direct,
but undocumented, variant:

   inet:setopts(Socket, [{send_timeout, N}])

It would be interesting to know what happens when you use the above
option and send a large binary all in one go, e.g.:

   gen_tcp:send(Socket, Large_binary)

and the socket blocks halfway through the binary. It's not documented,
so who knows... I haven't investigated.

See also:


More information about the erlang-questions mailing list