How can I send a message to another node?

余生长醉 提交于 2019-12-06 00:08:13

问题


I want to implement a simple chat room in which two nodes can send message to each other synchronous. There is not a node that plays a role of server.

Can I use ! to send a message to another node, if i have the pid of the process on this node by function of spawn(Node,Module,Fun,Args)?


回答1:


You can send to processes at another node just the same you would do with a process local to the same node. The trick is of course you need to have the process id. But you can also send to a process registered at another node by using the tuple {RegisteredName, NodeName}, e.g.

register(a, self()), {a, node()} ! foo.

will send a message to yourself.The same syntax works across nodes.

A more elaborate example

In the first 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

In the second 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>

And again in the first shell:

(one@grannysmith)2> flush().
Shell got good_day
ok


来源:https://stackoverflow.com/questions/16913436/how-can-i-send-a-message-to-another-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!