如何发送消息到另一个节点? [英] How can I send a message to another node?

查看:135
本文介绍了如何发送消息到另一个节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个简单的聊天室,其中两个节点可以相互发送消息同步。没有一个扮演服务器角色的节点。

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.

我可以使用向另一个发送消息节点,如果我通过 spawn(Node,Module,Fun,Args)的功能在该节点上具有pid的过程

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

推荐答案

您可以发送到另一个节点上的进程,与对同一节点本地进程的处理方式相同。当然,你需要具有进程标识。但是也可以通过使用元组{RegisteredName,NodeName}发送到在另一个节点上注册的进程。

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.

更精细的例子

在第一个shell中:

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

在第二个shell中:

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>

再次在第一个shell中:

And again in the first shell:

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

这篇关于如何发送消息到另一个节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆