我想实现一个简单的聊天室,其中两个节点可以同步向对方发送消息。没有一个节点充当服务器的角色。
我可以用吗!
向另一个节点发送消息,如果我通过以下函数获得该节点上进程的 pidspawn(Node,Module,Fun,Args)
?
您可以发送到另一个节点上的进程,就像发送到同一节点的本地进程一样。当然,诀窍是你需要有进程 ID。但是您也可以使用元组 {RegisteredName, NodeName} 发送到在另一个节点注册的进程,例如
register(a, self()), {a, node()} ! foo.
将向您自己发送一条消息。相同的语法适用于跨节点。
一个更详细的例子
在第一个外壳中:
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
在第二个外壳中:
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>
再次在第一个 shell 中:
(one@grannysmith)2> flush().
Shell got good_day
ok
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)