In the previous article, the registration process associated atoms have global scope, where the global refers to the current Erlang virtual machine, in the distributed, is the current distributed node. Therefore, registering the process-associated atoms in one node cannot be used directly in another node, but must be used with the target node.
Copy Code code as follows:
{regname, Node}! {messages}.
Example
Start a Server node first
Copy Code code as follows:
And then operate in the Erlang Shell.
First, briefly introduce several common functions
Copy Code code as follows:
% View current node
Node ().
% => ' server@gentoo-pc '
% View all connected nodes
Nodes ().
% => []% no other nodes are connected at this time
% to see if the current node is alive
Is_alive ().
% => True
And get to the point.
Copy Code code as follows:
% to start the last program in the previous article
Test:start ().
% waiting for the new message.
% => True
% current node can use TESTP Atom
TESTP! Message.
% New Message:message
% waiting for the new message.
% => Message
Then start another Client node
Copy Code code as follows:
In the new Erlang Shell
Copy Code code as follows:
Nodes ().
% => []% node not connected at this time
% The current node cannot directly use this atom's
TESTP! {}.
% * * * Exception Error:bad argument
% in operator!/2
% called as TESTP! {}
% need to work with target node
{TESTP, ' server@gentoo-pc '}! {}.
% => {}% statement return value
At this point, the server node receives the message and prints out
Copy Code code as follows:
% New message: {}
% waiting for the new message.
Two nodes will remain connected after the first connection between the nodes
In the Client node
Copy Code code as follows:
Nodes ().
% => [' server@gentoo-pc ']
In the Server node
Copy Code code as follows:
Nodes ().
% => [' client@gentoo-pc ']
End
Of course, this is only a method, because the call function is wrapped in the module, so you can use a remote call to invoke the Test:call method on the Server node.
Functions can be invoked remotely using the CALL/4 method in the RPC module
Copy Code code as follows:
% perform apply on node node (Module, Function, Args)
The% call returns result when the call fails, and returns {BADRPC, Reason}
-spec Rpc:call (Node, Module, Function, Args}-> Result | {BADRPC, Reason}
In the Client node
Copy Code code as follows:
Rpc:call (' server@gentoo-pc ', test, call, [' Message from other node ']).