taw
taw

Reputation: 18871

Erlang gen_tcp and line i/o

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?

Upvotes: 5

Views: 1088

Answers (2)

seeekr
seeekr

Reputation: 101

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])

Upvotes: 1

marcelog
marcelog

Reputation: 7180

Have you tried using

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

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

Cheers!

Upvotes: 7

Related Questions