如何将消息发送到另一个节点?

Des*_*.Me 7 erlang

我想实现一个简单的聊天室,其中两个节点可以相互同步发送消息.没有一个节点扮演服务器角色.

我是否可以使用!向另一个节点发送消息,如果我有这个节点上的进程的pid功能spawn(Node,Module,Fun,Args)

小智 16

您可以发送到另一个节点上的进程,就像对同一节点本地进程一样.当然,你需要拥有进程ID.但是您也可以使用元组{RegisteredName,NodeName}发送到在另一个节点注册的进程,例如

register(a, self()), {a, node()} ! foo.
Run Code Online (Sandbox Code Playgroud)

将向自己发送消息.相同的语法在节点之间起作用.

一个更详细的例子

在第一个shell中:

erl -sname one
Erlang R15B01 (erts-5.9.1) [source] [smp:8:8] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1  (abort with ^G)
one@grannysmith)1> (one@grannysmith)1> register(hello_server, self()).
(one@grannysmith)2>
true
Run Code Online (Sandbox Code Playgroud)

在第二个shell中:

erl -sname two
Erlang R15B01 (erts-5.9.1) [source] [smp:8:8] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1  (abort with ^G)
two@grannysmith)1> (one@grannysmith)1> {hello_server, 'one@grannysmith'} ! good_day.
good_day
(two@grannysmith)2>
Run Code Online (Sandbox Code Playgroud)

再次在第一个shell中:

(one@grannysmith)2> flush().
Shell got good_day
ok
Run Code Online (Sandbox Code Playgroud)

  • @ Despicable.Me http://learnyousomeerlang.com/是一本关于Erlang的非常好的在线书籍,还有一个印刷版本.否则只需查看亚马逊. (4认同)