Solution 11-3
Here is a suggested solution for Étude 11-3. Since the bulk of the code is identical to the previous étude, the only code shown here is the added and revised code.
%% @doc Connect to a named server
connect
(
ServerName
)
->
Result
=
net_adm
:
ping
(
ServerName
),
case
Result
of
pong
->
io
:
format
(
"Connected to server.
~n
"
);
pang
->
io
:
format
(
"Cannot connect to
~p
.
~n
"
,
[
ServerName
])
end
.
%% Wrapper to hide internal details when getting a weather report
report
(
Station
)
->
gen_server
:
call
({
global
,
weather
},
Station
).
%% Wrapper to hide internal details when getting a list of recently used
%% stations.
recent
()
->
gen_server
:
call
({
global
,
weather
},
recent
).
%%% convenience method for startup
start_link
()
->
gen_server
:
start_link
({
global
,
?
SERVER
},
?
MODULE
,
[],
[]).
%%% gen_server callbacks
init
([])
->
inets
:
start
(),
{
ok
,
[]}.
handle_call
(
recent
,
_
From
,
State
)
->
{
reply
,
State
,
State
};
handle_call
(
Request
,
_
From
,
State
)
->
{
Reply
,
NewState
}
=
get_weather
(
Request
,
State
),
{
reply
,
Reply
,
NewState
}.
handle_cast
(_
Message
,
State
)
->
io
:
format
(
"Most recent requests:
~p
\n
"
,
[
State
]),
{
noreply
,
State
}.
Get Études for Erlang now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.