//初始化udp
GCDAsyncUdpSocket *tempSocket=[[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
self.udpSocket=tempSocket;
//绑定端口
NSError *error = nil;
if (![self.udpSocket bindToPort:3456 error:&error]){
NSLog(@"绑定端口失败");
return;
}
//发送广播设置
if(![self.udpSocket enableBroadcast:YES error:&error]){
NSLog(@"广播使能设置失败");
return;
}
//加入群里,能接收到群里其他客户端的消息
if(![self.udpSocket joinMulticastGroup:@"239.55.55.55" error:&error]){
NSLog(@"加入组播失败");
return;
}
//启动接收线程
if(![self.udpSocket beginReceiving:nil]){
NSLog(@"启动接收线程失败");
return;
}
NSData *msg = [@"get" dataUsingEncoding:NSUTF8StringEncoding];
[self.udpSocket sendData:msg toHost:@"239.55.55.55" port:3456 withTimeout:-1 tag:10];
http://bbs.csdn.net/topics/391964821
您好,我也遇到了同样的问题。
可能的原因:因为ios里将组播包的TTL值(Time to live:网络数据包的生存周期,通常也叫“跳数”)默认设置为1,即只经过了一跳后这个包就不被转发了,所以上模拟器上能发出来,真机就有问题了,您可以通过Wireshark软件查看模拟器发出来的数据包,看看Time to live值是否为1。
针对上面可能的原因的解决方法:需要重新设置组播的TTL值(1~255,一般常见UDP为64)。但是GCDAsyncUdpSocket这个类好像没有(也有可能是我没找到)类似于setsocketopt设置socket属性的方法,因此本人使用了原生态的socket去创建了一个socket并设置TTL值为64后发现可以了。
本人还存在问题:有的时候能发出来,但是有的时候还是发不出来,不知道为什么!!!
//-----------------------以下是使用标准socket发送组播的代码--------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
//sock初始化
//按一个Button发送组播,packet_udp_info是一个结构体类型的变量,您在使用的时候自定义一个buffer吧
写在最后:本人也是初学者,有什么不对的地方还请大神们指正,谢谢!!!!!