[erlang-questions] Line Receiver example?

Joe Armstrong erlang@REDACTED
Mon Apr 27 21:44:50 CEST 2009


A basic server looks something like this:

start_server() ->
    {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4},
					 {active, true}]),
    {ok, Socket} = gen_tcp:accept(Listen),
    gen_tcp:close(Listen),
    loop(Socket).

loop(Socket) ->
    receive
	{tcp, Socket, Bin} ->
	    io:format("Server received binary = ~p~n",[Bin]),
	    ...
	    loop(Socket);
	{tcp_closed, Socket} ->
	    io:format("Server socket closed~n")
    end.

Now you want to call a function every time a "line" is received
If the function is F you can modify the code as follows:

(Compare this with the original)

start_server(F) ->
    {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4},
					 {active, true}]),
    {ok, Socket} = gen_tcp:accept(Listen),
    gen_tcp:close(Listen),
    loop(Socket, F).

loop(Socket, F) ->
    receive
	{tcp, Socket, Bin} ->
	    io:format("Server received binary = ~p~n",[Bin]),
	    ...
	    F(Bin),	
	    loop(Socket, F);
	{tcp_closed, Socket} ->
	    io:format("Server socket closed~n")
    end.

Once you see how the arguments flow it should be easy to change the
examples in the book :-)

To start do something like

Now define your handling fun

myfun(Bin) ->
    ....

start with:

spawn(fun() -> start_server(fun myfun/1).

	
The idea of what a "line" is can be changed by setting different
options when opening the socket.

Cheers

/Joe




On Mon, Apr 27, 2009 at 6:31 PM, Jarrod Roberson <jarrod@REDACTED> wrote:
> I am desperately trying to convert the example code from the SHOUTCast
> server example in the Programming Erlang book to call a function on every
> line received instead of the way it works in the book.
> I am coming from using the Twisted framework for Python and trying to port
> some applications, Twisted has a "Line Receiver" protocol that calls a
> function when every line is detected.
> It makes writing basic protocols very easy. I have been unsuccessful in
> trying to accomplish the same thing with Erlang.
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list