简单实现了一个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 .