如何在Erlang中使用gen_udp进行多播? [英] How to multicast using gen_udp in Erlang?

查看:224
本文介绍了如何在Erlang中使用gen_udp进行多播?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you use gen_udp in Erlang to do multicasting? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.

推荐答案

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

Here is example code on how to listen in on Bonjour / Zeroconf traffic.

-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中使用gen_udp进行多播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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