Erlang简单服务器问题
当我学习 Erlang 时,我正在尝试解决 ex. 4.1(“Echo 服务器”)来自“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.
不幸的是,我有一些问题。打开按预期工作,它会生成一个新进程并显示“服务器已准备就绪”消息。但是,当我尝试使用打印功能(例如 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()
停止服务器时,我收到另一个错误
** exception error: bad argument
in function echo:stop/0
有人可以解释一下,这里发生了什么?我是 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您的
loop/0
函数收到print
消息时,您再次调用start/0
,这会产生新进程并尝试将其注册为echo再次。它会导致您的服务器挂掉,并且新服务器未注册为
echo
,因此您无法再通过print/1
函数向其发送消息。When your
loop/0
function receiveprint
message you callstart/0
again which spawns new process and trying to register it asecho
again. It causes your server dies and new one is not registered asecho
, so you can't send message to it byprint/1
function any more.