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)
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With