你如何在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}}
停止收听该组.