您的位置:首页 > 其它

欢迎使用CSDN-markdown编辑器

2015-05-15 15:19 169 查看

关于AsyncUdpSocket同wifi下收不到消息

这2天有空的时候弄了个小demo,在2台iphone上,同一wifi下使用udp协议进行发送,接受消息。然后就碰到同一wifi下有时候会收不到消息的情况。

不废话,直接先上代码(server端):

//初始化udp
AsyncUdpSocket *tempSocket=[[AsyncUdpSocket alloc] initWithDelegate:self];
self.udpSocket=tempSocket;
//绑定端口
NSError *error = nil;
[self.udpSocket bindToPort:4333 error:&error];

//发送广播设置
[self.udpSocket enableBroadcast:YES error:&error];

//加入群里,能接收到群里其他客户端的消息
[self.udpSocket joinMulticastGroup:@"192.168.1.111" error:&error];

//启动接收线程
[self.udpSocket receiveWithTimeout:-1 tag:0];


客户端发送一个消息

BOOL  res = [self.udpSocket sendData:[sendString dataUsingEncoding:NSUTF8StringEncoding]
toHost:@"192.168.1.111"
port:4333
withTimeout:-1
tag:0];

NSLog(@"send msg is:%@",sendString);
self.statusLb.text = sendString;
if (!res) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"发送失败"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:nil];
[alert show];
}


客户端发送一条消息后,服务端死活收不到消息。更奇怪的上2台设备更换另外一个wifi的时候,就收得到。同样的代码为什么一个收得到,另外一个wifi下收不到呢?

后来,请教了下公司的一个大牛,一句话就搞定了:2台设备都在浏览器下先输入路由地址(比如:192.168.1.1)访问下,然后就可以再试下收不收得到了。

为什么?因为要先连通下网络!! =。= 这个。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  udp 收不到消息