EP Exercise 4-1: An Echo Server

My solution for Exercise 4-1 in the book Erlang Programming.

%%
%% Erlang Programming Exercise 4-1
%%

-module(echo).
-export([start/0,print/1,stop/0,loop/0]).

start() ->
    %% function specified in spawn/3 must be exported !!
    Pid = spawn(echo, loop, []),
    register(echo_server, Pid),
    ok. 

stop() ->
    echo_server ! stop,
    ok. 

print(Term) ->
    echo_server ! {print, Term},
    ok. 

loop() ->
    receive
        {print, Msg} -> io:format("~s~n",[Msg]),
                        loop();
        stop -> true
    end.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s