How to send a message to another node?

I want to implement a simple chat room in which two nodes can send messages to each other synchronously. There is no node that acts as a server.

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

+6
source share
1 answer

You can send processes to another node the same as with a process local to the same node. The trick, of course, must have a process id. But you can also submit a process registered to another node using the {RegisteredName, NodeName} tuple, for example.

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

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

More detailed 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 
+13
source

Source: https://habr.com/ru/post/946484/


All Articles