Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send a message to another node?

Tags:

erlang

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)?

like image 630
Despicable.Me Avatar asked Jun 04 '13 08:06

Despicable.Me


1 Answers

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
like image 187
Jan Henry Nystrom Avatar answered Oct 03 '22 03:10

Jan Henry Nystrom