官方的例子:
test_impl(udp_multicast_join) {
int r;
uv_udp_send_t req;
uv_buf_t buf;
struct sockaddr_in addr = uv_ip4_addr("239.255.0.1", test_port);
r = uv_udp_init(uv_default_loop(), &server);
assert(r == 0);
r = uv_udp_init(uv_default_loop(), &client);
assert(r == 0);
/* bind to the desired port */
r = uv_udp_bind(&client, addr, 0);
assert(r == 0);
/* join the multicast channel */
r = uv_udp_set_membership(&client, "239.255.0.1", null, uv_join_group);
assert(r == 0);
r = uv_udp_recv_start(&client, alloc_cb, cl_recv_cb);
assert(r == 0);
buf = uv_buf_init("ping", 4);
/* server sends "ping" */
r = uv_udp_send(&req, &server, &buf, 1, addr, sv_send_cb);
assert(r == 0);
assert(close_cb_called == 0);
assert(cl_recv_cb_called == 0);
assert(sv_send_cb_called == 0);
/* run the loop till all events are processed */
uv_run(uv_default_loop());
assert(cl_recv_cb_called == 1);
assert(sv_send_cb_called == 1);
assert(close_cb_called == 2);
return 0;
}
这段代码有个问题,multicast时本机也能收到数据.设置uv_udp_set_multicast_loop(&server, 0);也不起作用.
从代码上看,server没有bind,问题应该是出在这里.加上如下两句:
struct sockaddr_in addr2 = uv_ip4_addr("0.0.0.0", test_port 2);
uv_udp_bind(&server, addr2, 0);
再测试,本机收不到数据了.再加上uv_udp_set_multicast_loop(&server, 1) 本机又可以收到.测试环境是centos5.6,不同的环境可能表现不一样.官方写例子的时候应该是没有问题的.不过为了安全,所有的socket都bind一下好了.
阅读(4985) | 评论(0) | 转发(0) |