簡體   English   中英

Erlang簡單的服務器問題

[英]Erlang simple server problem

當我學習Erlang時,我正試圖解決前任問題。 4.1(“回聲服務器”)來自“Erlang編程”一書(由O'Reilly撰寫),我遇到了問題。 我的代碼看起來像這樣:

-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.

不幸的是,我有一些問題。 打開按預期工作,它會生成一個新進程並顯示“服務器就緒”消息。 但是當我嘗試使用print函數時(例如echo:print("Some message.").例如)我得到了結果,但它不像我想的那樣工作。 它將我的消息打印為列表(而不是字符串)並生成

=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}]}

錯誤信息。 而且,當我嘗試通過echo:stop()停止服務器時echo:stop()我得到了另一個錯誤

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

任何人都可以解釋一下,這里發生了什么? 我是Erlang的新手,此時似乎很難掌握。

當你的loop/0函數接收到print消息時,你再次調用start/0 ,它會生成新進程並嘗試再次將其注冊為echo 它會導致您的服務器死機而新的服務器沒有注冊為echo ,因此您無法再通過print/1函數向其發送消息。

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM