[英]How to send a message from one node to another node in Erlang OTP
We can send a message to an existing process via the shell as below.我们可以通过 shell 向现有进程发送消息,如下所示。 I register a process by its Username here (ex: alice) code:我在这里通过其用户名注册一个进程(例如:alice)代码:
start_link(Username) ->
gen_server:start_link({local, Username}, ?MODULE, [Username], []).
stop(Username)->
gen_server:stop(Username).
init([Username]) ->
io:format("~p connected...",[Username]),
{ok, #chat_server_state{
username = Username
}}.
Process started as below:流程开始如下:
chat_client:start_link(alice).
alice connected...{ok,<0.143.0>}
I sent message hello to process alice and result as below:我发送消息 hello 来处理 alice,结果如下:
alice ! hello. %%sent 'hello' atom to 'alice' process
hello %% result
My problem is if I started two nodes with same coockie and connected both nodes with net_kernel, still why I cant send a message from one node to other node using the registered process name (instead of pid) as above procedure.我的问题是,如果我使用相同的 coockie 启动两个节点并将两个节点连接到 net_kernel,仍然为什么我不能使用注册的进程名称(而不是 pid)将消息从一个节点发送到另一个节点,如上述过程。
my code: here I register the process with the node name.我的代码:在这里我使用节点名称注册进程。
start_link(Username) ->
gen_server:start_link({local, node()}, ?MODULE, [Username], []).
stop(Username)->
gen_server:stop(Username).
init([Username]) ->
io:format("~p connected...",[Username]),
{ok, #chat_server_state{
username = Username
}}.
I started alice process on alice@... node.我在 alice@... 节点上启动了 alice 进程。
(alice@DESKTOP-RD414DV)79> chat_client:start_link(alice).
alice connected...{ok,<0.280.0>}
This is where this alice process is registered with its node name这是这个 alice 进程使用其节点名称注册的地方
** Registered procs on node 'alice@DESKTOP-RD414DV' **
Name Pid Initial Call Reds Msgs
'alice@DESKTOP-RD414D <0.250.0> chat_client:init/1 54 0
Why can't I send a message from this alice@..... node to another node (ex: bob@DESKTOP-RD414D by 'bob@DESKTOP-RD414D'. hello. )为什么我不能从这个 alice@..... 节点向另一个节点发送消息(例如:bob@DESKTOP-RD414D by 'bob@DESKTOP-RD414D'。你好。 )
(alice@DESKTOP-RD414DV)71> whereis('alice@DESKTOP-RD414DV').
<0.250.0>
I get this error:我收到此错误:
(alice@DESKTOP-RD414DV)50> 'bob@DESKTOP-RD414DV' ! heelo.
** exception error: bad argument
in operator !/2
called as 'bob@DESKTOP-RD414DV' ! heelo
To send a message to a registered process in any node, you can use the {Name:: atom(), Node:: node()}: Message:: term()
syntax:要向任何节点中的已注册进程发送消息,可以使用{Name:: atom(), Node:: node()}: Message:: term()
语法:
1> register(shell, self()).
true
2> shell ! test.
test
3> flush().
Shell got test
ok
4> {shell, node()} ! test.
test
5> flush().
Shell got test
ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.