Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Erlang简单服务器问题_Erlang - Fatal编程技术网

Erlang简单服务器问题

Erlang简单服务器问题,erlang,Erlang,在学习Erlang的过程中,我试图解决《Erlang编程》一书(由O'Reilly编写)中的ex.4.1(“Echo服务器”),我遇到了一个问题。 我的代码如下所示: -module(echo). -export([start/0, print/1, stop/0, loop/0]). start() -> register(echo, spawn(?MODULE, loop, [])), io:format("Server is ready.~n"). loop()

在学习Erlang的过程中,我试图解决《Erlang编程》一书(由O'Reilly编写)中的ex.4.1(“Echo服务器”),我遇到了一个问题。 我的代码如下所示:

-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.
不幸的是,我有一些问题。启用该选项将按预期工作,它将生成一个新进程并显示“服务器就绪”消息。但当我尝试使用打印功能时(比如
echo:print(“Some message”)。
this,例如),我得到了结果,但它不能像我希望的那样工作。它将我的消息打印为列表(而不是字符串),并生成

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

谁能给我解释一下,这是怎么回事?我是Erlang的新手,现在似乎很难理解。

当您的
循环/0
函数收到
打印
消息时,您再次调用
启动/0
,这会产生新的进程,并再次尝试将其注册为
回音。这会导致您的服务器死亡,而新服务器未注册为
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.
loop()->
接收
{打印,Msg}->
io:format(“您发送了一条消息:~w.~n”,[Msg]),
循环();%
io:format(“服务器已关闭~n”);
_ ->
io:格式(“未识别命令~n”),
循环()
结束。

字符串在erlang中表示为列表。当然你是对的,但既然没有不能显示的字符,为什么它显示为列表而不是字符串?但这只是一件事,不是最重要的,问题仍然是一样的。@Hynek解释了主要问题。字符串是整数列表,因此
“abc”
[97,98,99]
相同。所以erlang并不真正“知道”整数列表是整数列表还是字符串。在格式字符串中使用
~w
,只需将其打印为列表。如果使用
~p
,它将测试整数列表是否可以是可打印字符串,如果可以,则将它们打印为字符串。这就是贝壳的作用。是的,这是故意的,不是一个bug。将字符串作为列表使它们非常容易使用。事实上,使用~p参数,打印工作与预期一样。谢谢你的建议。当然,就是这么简单。非常感谢,我似乎很累,没有注意到明显的错误。再次感谢你。
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.