Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang simple server problem

Tags:

erlang

As I learn Erlang, I'm trying to solve ex. 4.1 ("An Echo server") from "Erlang Programming" book (by O'Reilly) and I have a problem. My code looks like that:

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

start() ->
    register(echo, spawn(?MODULE, loop, [])),
    io:format("Server is ready.~n").

loop() ->
    receive
        {print, Msg} ->
            io:format("You sent a message: ~w.~n", [Msg]),
            start();
        stop ->
            io:format("Server is off.~n");
        _ ->
            io:format("Unidentified command.~n"),
            loop()
    end.

print(Msg) -> ?MODULE ! {print, Msg}.

stop() -> ?MODULE ! stop.

Unfortunatelly, I have some problems. Turning on works as expected, it spawns a new process and display "Server is ready" message. But when I try to use print function (like echo:print("Some message."). that, for example) I got result, but it doesn't work like I'd like to. It prints my message as a list (not as a string) and it generates

=ERROR REPORT==== 18-Jul-2010::01:06:27 ===
Error in process <0.89.0> with exit value: {badarg,[{erlang,register,[echo,<0.93.0>]},{echo,start,0}]}

error message. Moreover, when I try to stop server by echo:stop() I got another error

** exception error: bad argument
 in function  echo:stop/0

Could anybody explain me, what's going on here ? I am new to Erlang and it seems to be quite difficult to grasp for me at this time.

like image 271
Zbigniew Avatar asked Jul 17 '10 23:07

Zbigniew


1 Answers

When your loop/0 function receive print message you call start/0 again which spawns new process and trying to register it as echo again. It causes your server dies and new one is not registered as echo, so you can't send message to it by print/1 function any more.

loop() ->
    receive
        {print, Msg} ->
            io:format("You sent a message: ~w.~n", [Msg]),
            loop();   % <-- just here!
        stop ->
            io:format("Server is off.~n");
        _ ->
            io:format("Unidentified command.~n"),
            loop()
    end.
like image 143
Hynek -Pichi- Vychodil Avatar answered Sep 21 '22 02:09

Hynek -Pichi- Vychodil