繁体   English   中英

如何在 Erlang 中使用 gen_udp 进行多播?

[英]How to multicast using gen_udp in Erlang?

你如何在 Erlang 中使用gen_udp进行多播 我知道它在代码中,它背后没有文档。 发送数据是显而易见的和简单的。 我想知道如何添加会员资格。 不仅在启动时添加成员资格,而且在运行时添加成员资格也很有用。

以下是关于如何监听 Bonjour / Zeroconf 流量的示例代码。

-module(zcclient).

-export([open/2,start/0]).
-export([stop/1,receiver/0]).

open(Addr,Port) ->
   {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]),
   inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]),
   S.

close(S) -> gen_udp:close(S).

start() ->
   S=open({224,0,0,251},5353),
   Pid=spawn(?MODULE,receiver,[]),
   gen_udp:controlling_process(S,Pid),
   {S,Pid}.

stop({S,Pid}) ->
   close(S),
   Pid ! stop.

receiver() ->
   receive
       {udp, _Socket, IP, InPortNo, Packet} ->
           io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]),
           receiver();
       stop -> true;
       AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]),
           receiver()
   end. 

多播发送已被应答,接收需要订阅多播组。

它(仍然)似乎没有记录,但之前已经在 erlang-questions 邮件列表中提到过。 http://www.erlang.org/pipermail/erlang-questions/2003-March/008071.html

    {ok, Socket} = gen_udp:open(Port, [binary, {active, false},
                                       {reuseaddr, true},{ip, Addr}, 
                                       {add_membership, {Addr, LAddr}}]).

其中, Addr是组播组, LAddr是本地接口。 (代码由 mog 提供)

上面使用的相同选项可以传递给inet:setopts包括{drop_membership, {Addr, LAddr}}以停止侦听组。

我试着让这个例子在我的 PC 上运行。 如果我总是通过打开接收套接字收到消息 {error,eaddrnotavail},会发生什么?

示例 1:这有效:

{ok, Socket} = gen_udp:open(?PORT, [{reuseaddr,true}, {ip,?SERVER_IP},
               {multicast_ttl,4}, {multicast_loop,false}, binary]),

示例 2:获取运行时错误:

{ok, Socket} = gen_udp:open(?PORT, [{reuseaddr,true}, {ip,?MULTICAST_IP},
               {multicast_ttl,4}, {multicast_loop,false}, binary]),

% --> {错误,eaddrnotavail}

-define(SERVER_IP, {10,31,123,123}). % The IP of the current computer
-define(PORT, 5353).
-define(MULTICAST_IP, {224,0,0,251}). 

多播由 IP 地址指定

erlang 和所有语言都是一样的。 IP 地址 224.0.0.0 到 239.255.255.255 是多播地址。

在该范围内选择一个地址,检查您没有与已分配的地址重叠,然后就可以开始了。

http://www.iana.org/assignments/multicast-addresses

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM