Skip to content

Instantly share code, notes, and snippets.

@thom-nic
Created February 27, 2011 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thom-nic/846538 to your computer and use it in GitHub Desktop.
Save thom-nic/846538 to your computer and use it in GitHub Desktop.
Erlang echo script
%%% Sends a message back & forth
%%% Author: Thom Nichols
%%%
%%% Remote server communication demo.
%%% Use start_listener/1 to register a listener on a remote or local node.
%%% use send/2 to send a messge to a node and listen for its response.
-module(echo).
-author('Thom Nichols').
-import(erlang).
-import(io).
-import(global).
-export([
send/0, send/1, send/2,
reply/0,
start_listener/0, start_listener/1
]).
send() ->
send(node()).
send(Node) ->
send(Node, erlang:localtime()).
%%% Send a message to the given node.
send(Node, Msg) ->
io:format('Sending message "~w" to ~w...~n',[Msg,Node]),
Envelope = {Msg,self()},
if
Node /= node() -> global:send(echo, Envelope);
true -> {echo, Node} ! {Msg, self()}
end,
receive
{echo, Node, Resp} ->
io:format('Response from ~w: ~w~n',[Node,Resp]),
ok;
Other ->
io:format('Unexpected response: ~p~n', [Other]),
ok
after 10000 ->
io:format('Timeout waiting for response from ~w~n',[Node]),
{error, timeout}
end.
reply() ->
receive
{Msg, Pid} when is_pid(Pid) ->
io:format('Sending response ~w to ~w...~n',[Msg,Pid]),
Pid ! {echo,node(),Msg};
Other ->
io:format('Unexpected message: ~p~n', [Other]),
ok
after 10000 ->
% io:fwrite('Timeout, retrying...~n',[]),
reply()
end.
%%% Create a listener process on this node
start_listener() ->
start_listener(node()).
%%% Create a listener process on the given node.
%%% On a non-local node, global:register_name is used
%%% to globally-register a unique process name
start_listener(Node) ->
Pid = spawn(Node, echo, reply, []),
if
Node /= node() ->
global:register_name(echo, Pid),
io:format('registered global.~n');
true -> register( echo, Pid )
end,
io:format('Listener running on ~w~n',[Node]),
{ok, echo}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment