无法通过gen_udp获取数据

时间:2016-07-12 08:16:50

标签: sockets erlang udp

我在远程服务器上运行tcpdump -i eth0 -vv ip6并查看此类数据包

11:10:36.712804 IP6 (hlim 1, next-header UDP (17) payload length: 103) fe80::f816:3eff:fe94:a348.57100 > ff3c::8500:2345.57100: [udp sum ok] UDP, length 95

但是当我打开Socket

{ok, Socket} = gen_udp:open(57100, [binary, {active, true}, {ip, any}, inet6, {reuseaddr, true}])

{ok, Socket} = gen_udp:open(57100, [binary, {active, true}, {ip, any}, inet6, {multicast_ttl, 225}, {multicast_loop, false}, {reuseaddr, true}])

{ok, Socket} = gen_udp:open(57100, [binary, {active, true}, {ip, {65340,0,0,0,0,0,34048,9029}}, inet6, {multicast_ttl, 225}, {multicast_loop, false}, {reuseaddr, true}])

{65340,0,0,0,0,0,34048,9029} = <<"FF3C:0000:0000:0000:0000:0000:8500:2345">>

并以这种方式等待消息

subscribe_on_stream() -> 
    %% {ok, Socket} = gen_udp:open(57100, [binary, {active, true}, {ip, IP}, inet6, {multicast_ttl, 225}, 
    %% {multicast_loop, false}, {reuseaddr, true}]), 
    {ok, Socket} = gen_udp:open(Port, [binary, {active, true}, {reuseaddr, true}]), 
    io:format("self: ~p line: ~p~n", [self(), ?LINE]), 
    subscribe_loop(Socket). 

subscribe_loop(Socket) -> 
    receive 
       Any -> 
           io:format("~p~n", [Any])
    end.

1 个答案:

答案 0 :(得分:0)

问题出在subscribe_loop(Socket)上。它实际上并没有循环。你调用函数一次,它返回就是它。您需要递归调用subscribe_loop(...)来进行循环。

以下是如何编写一个等待消息的非常简单的服务器的示例。

https://www.erlang.org/course/concurrent-programming

解决方案:

subscribe_loop(Socket) -> 
    receive 
       Any -> 
           io:format("~p~n", [Any]),
           subscribe_loop(Socket)
    end.