Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang gen_tcp and line i/o

Tags:

erlang

Is there any way to read whole lines from a socket in Erlang, or do I need to implement line buffering manually on top of gen_tcp:recv?

like image 641
taw Avatar asked Jun 20 '12 01:06

taw


2 Answers

Have you tried using

inet:setopts(Socket, [{packet, line}])

See: http://www.erlang.org/doc/man/inet.html#setopts-2

Cheers!

like image 181
marcelog Avatar answered Oct 15 '22 18:10

marcelog


There is no need to implement line buffering yourself.

gen_tcp:listen/2 accepts {packet, line} for its Options argument, which will put the socket into line mode and so calls to gen_tcp:recv will block until a complete line has been read.

gen_tcp:listen(Port, [{packet, line}])

Make sure that your buffer size set via the {buffer, Size} option to the same call (or inet:setopts/2) is big enough that it will fit all of your lines, otherwise they will be truncated.

Or, if using Elixir, this should get you started:

:gen_tcp.listen(port, [packet: :line, buffer: 1024])
like image 42
seeekr Avatar answered Oct 15 '22 17:10

seeekr