我想实现一个简单的聊天室,两个节点可以在其中同步发送消息。没有扮演服务器角色的节点。
如果我通过以下函数在该节点上拥有进程的 pid,我可以!
用来向另一个节点发送消息spawn(Node,Module,Fun,Args)
吗?
我想实现一个简单的聊天室,两个节点可以在其中同步发送消息。没有扮演服务器角色的节点。
如果我通过以下函数在该节点上拥有进程的 pid,我可以!
用来向另一个节点发送消息spawn(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