官方的例子:
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一下好了.
阅读(5205) | 评论(0) | 转发(0) |