作者:一米静心的阳光 | 来源:互联网 | 2023-06-17 17:45
简单实现了一个echo服务器-module(echo).-export([start0,loop0]).start()-Pidspawn(echo,loop,[
简单实现了一个echo 服务器
-module(echo).
-export([start/0,loop/0]).
start() ->
Pid = spawn(echo,loop,[]),
Pid ! {self(),‘Hello Word‘},
receive
{Pid,Msg} ->
io:format(‘~w~n‘,[Msg])
end,
Pid ! stop.
loop() ->
receive
{FromOther,Msg} ->
io:format("~w~n",[Msg]),
FromOther!{self(),‘Loop Proccess Send to You !‘},
loop();
{stop} ->
%%io:format(‘~w~n‘,[loop_stop]),
true
end.
输出:
29> echo:start().
‘Hello Word‘
‘Loop Proccess Send to You !‘
stop
30>
其中 stop 是主进程的返回值
echo_server2 :
这是一个简单用于等待外部信息的echo server
-module(echo_server).
-export([start/0,print/1,stop/0,loop/0]).
start() ->
Pid = spawn(echo_server , loop , []),
register(sub1,Pid),
{ok,Pid}.
loop() ->
receive
{print,A} ->
io:format("~p.~n",[A]),
loop();
stop ->
true;
Other ->
io:format("~p~n",[Other]),
loop()
end.
print(A) ->
sub1 ! {print,A},
true .
stop() ->
sub1 ! stop ,
%%
true .