文章中说到, 注册进程关联的原子具有全局作用域, 这里的全局指的是当前 erlang 虚拟机, 在分布式中, 便是当前分布式节点. 因此, 在一个节点中注册进程关联的原子, 在另一个节点中是不能直接使用, 而必须配和目标节点使用.
{regname, node} ! {messages}.
例子
先启动一个 server 节点
erl -sname server
然后在 erlang shell 中操作
先简单介绍几个常用函数
% 查看当前节点
node().
% => 'server@gentoo-pc'
% 查看所有已连接的节点
nodes().
% => [] % 此时还未连接其它节点
% 查看当前节点是否存活
is_alive().
% => true
然后进入正题
% 启动上一篇文章中最后的那个程序
test:start().
% waiting for new message.
% => true
% 当前节点可以使用 testp 原子
testp ! message.
% new message: message
% waiting for new message.
% => message
然后启动另外一个 client 节点
erl -sname client
在新的 erlang shell 中
nodes().
% => [] % 此时未连接节点
% 当前节点无法直接使用这个原子的
testp ! {}.
% ** exception error: bad argument
% in operator !/2
% called as testp ! {}
% 需要配合目标节点一起使用
{testp, 'server@gentoo-pc'} ! {}.
% => {} % 语句返回值
此时, server 节点就会接收到消息, 并打印出
% new message: {}
% waiting for new message.
节点间首次连接后, 两个节点将会保持连接
在 client 节点中
nodes().
% => ['server@gentoo-pc']
在 server 节点中
nodes().
% => ['client@gentoo-pc']
结尾
当然, 这只是个方法, 由于在模块中定义了 call 函数包裹了起来, 所以可以使用远程调用, 调用 server 节点上的 test:call 方法.
可以使用 rpc 模块中的 call/4 方法远程调用函数
% 在 node 节点上执行 apply(module, function, args)
% 调用成功时返回 result, 调用失败时返回 {badrpc, reason}
-spec rpc:call(node, module, function, args} -> result | {badrpc, reason}
在 client 节点中
rpc:call('server@gentoo-pc', test, call, ['message from other node']).