area_server.erl
-module(area_server).
-export([loop/0]).
loop() ->
receive
{rectangle, Width, Ht} ->
io:format("Area of rectangle is ~p~n", [Width * Ht]),
loop();
{circle, R} ->
io:format("Area of circle is ~p~n", [3.14*R*R]),
loop();
Other ->
io:format("I do not know what the area of a ~p is ~n", [Other]),
loop()
end.
|
测试过程:
1> c(area_server).
{ok,area_server}
2> Pid = spawn(fun area_server:loop/0).
<0.39.0>
3> Pid ! {circle, 67}.
Area of circle is 14095.46
{circle,67}
第一次改进:
-module(area_server).
-export([loop/0, rpc/2]).
rpc(Pid, Request) ->
Pid ! {self(), Request},
receive
Response ->
Response
end.
loop() ->
receive
{From, {rectangle, Width, Ht}} ->
From ! {rectangle, Width*Ht},
loop();
{From, {circle, R}} ->
From ! {circle, 3.14*R*R},
loop();
{From, Other} ->
Error = "Sorry, error!",
From ! {Error,Other},
loop()
end.
|
测试:
4> c(area_server).
{ok,area_server}
6> Pid = spawn(fun area_server:loop/0).
<0.53.0>
7> area_server:rpc(Pid, sockes).
{"Sorry, error!",sockes,ok}
改进2:
-module(area_server).
-export([loop/0, rpc/2]).
rpc(Pid, Request) ->
Pid ! {self(), Request},
receive
{Pid, Response} ->
Response
end.
loop() ->
receive
{From, {rectangle, Width, Ht}} ->
From ! {self(), Width*Ht},
loop();
{From, {circle, R}} ->
From ! {self(), 3.14*R*R},
loop();
{From,Other} ->
From ! {self(), error, Other},
loop()
end.
|
测试:
2> c(area_server).
{ok,area_server}
3> Pid = spawn(fun area_server:loop/0).
<0.43.0>
4> area_server:rpc(Pid, {rectangle, 8, 6}).
48
改进3:
-module(area_server).
-export([start/0]).
start() ->
Pid = spawn(fun loop/0),
rpc(Pid, {rectangle, 8, 6}).
rpc(Pid, Request) ->
Pid ! {self(), Request},
receive
{Pid, Response} ->
Response
end.
loop() ->
receive
{From, {rectangle, Width, Ht}} ->
From ! {self(), Width*Ht},
loop();
{From, {circle, R}} ->
From ! {self(), 3.14*R*R},
loop();
{From,Other} ->
From ! {self(), error, Other},
loop()
end.
|
测试:
2> c(area_server).
{ok,area_server}
3> area_server:start().
48
4> area_server:start().
48
5>
阅读(1332) | 评论(1) | 转发(0) |