using a socket to send and receive

Roberto Ostinelli <>
Thu Aug 19 13:24:50 CEST 2010

dear list,

i need to use a socket both to receive and send data. the socket must
be listening for incoming data from TCP, but it needs also to receive
data to be sent from external processes when events occur. the socket
is in raw mode.

i'm using a binary protocol which specifies that the length of the
incoming data varies continuously.

my current solution is to use 2 processes, one to listen for incoming
data in passive mode, the other to listen for incoming erlang messages
from other processes, in a simple way as:

recv(Sock, Len) ->
	case gen_tpc:recv(Sock, Len) of
send(Sock) ->
		{send, DataToSend} -> gen_tpc:send(Sock, DataToSend)

i use passive mode since it is very simple to set the length of the
incoming data to wait for with gen_tpc:recv/2.

what i would like to do is to use a single process in {active, once}
mode, so that both messages received from the socket AND from the
external processes are treated within a same loop.

the solution would look something like:

sock_loop(Sock, Len) ->
	inet:setopts(Sock, [{active, once}, {recv_size, Len}]),
		{http, Sock, Data} ->
			% data received from TCP socket, do something with it
		{send, DataToSend} ->
			% data received from external processes, send it to socket
			gen_tpc:send(Sock, DataToSend)

problem is that the option 'recv_size' that i've specified here above
obviously does not exist, and i can't find how to set the length of
the packet to receive in the way that i can easily do with passive
mode and gen_tpc:recv/2. the sndbuf inet option does not seem to be
it, since it's a buffer size.

i've read the docs but i guess i have missed a point somewhere.

can anyone point me out on how to do this?

thank you,


More information about the erlang-questions mailing list