use*_*850 5 iphone udp xcode4.3
我有一个问题,我发送一个udp消息(广播)给客户端并得到答案,但这将显示两次.当我通过UDP监听器检查通信时,我只有一条消息.
可能是,有人可以告诉我如何解决这个问题.
我正在使用按钮开始发送消息!
#import "ViewController.h"
#import "GCDAsyncUdpSocket.h"
@interface ViewController ()
{
long tag;
GCDAsyncUdpSocket *udpSocket;
}
@end
@implementation ViewController
- (void)setupSocket
{ udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket bindToPort:1000 error:&error])
{
NSLog(@"Error binding: %@", error);
return;
}
if (![udpSocket beginReceiving:&error])
{
NSLog(@"Error receiving: %@", error);
return;
}
[udpSocket enableBroadcast:YES error: &error];
NSLog(@"Ready");
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (udpSocket == nil)
{
[self setupSocket];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)send:(id)sender{
NSString *host = @"192.168.2.255";
if ([host length] == 0)
{
NSLog(@"Address required");
return;
}
NSLog(@"%@",host);
int port = 8888;
NSString *msg = @"1,0,1,2";
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:tag];
NSLog(@"SENT (%i): %@", (int)tag, msg);
tag++;
}
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
NSLog(@"RECV: %@", msg);
tag++;
NSLog(@"%li",tag);
}
else
{
NSString *host = nil;
uint16_t port = 0;
[GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
NSLog(@"RECV: Unknown message from: %@:%hu", host, port);
}
}
@end
Run Code Online (Sandbox Code Playgroud)
这是输出!
2013-09-11 09:49:00.132 udptest[5145:907] 15
2013-09-11 09:49:08.218 udptest[5145:907] 192.168.2.255
2013-09-11 09:49:08.220 udptest[5145:907] SENT (15): 1,0,1,2
2013-09-11 09:49:08.319 udptest[5145:907] RECV: 0,0,0,0,0,0,0,0
2013-09-11 09:49:08.321 udptest[5145:907] 17
2013-09-11 09:49:08.323 udptest[5145:907] RECV: 0,0,0,0,0,0,0,0
2013-09-11 09:49:08.324 udptest[5145:907] 18
Run Code Online (Sandbox Code Playgroud)
如果有人能帮助我,我将非常感激.
Luc*_*caM 11
我有同样奇怪的不需要和未解决的行为:"发送者"发送一个广播UDP消息,"接收器"得到两个消息.
我尽可能多地调查了这些是我的发现:
1)Wireshark只获得一条UDP消息.
2)udpSocket:didReceiveData:fromAddress:withFilterContext:被激活两次!
3)使用[GCDAsyncUdpSocket getHost:port:fromAddress:]解析"address"参数会导致host = :: ffff:192.168.1.118第一次,而host = 192.168.1.118则是SECOND时间.
希望它会以某种方式有所帮助......
FIRST地址(参见第2点和第3点)是一个实际的IPv6地址.所以我猜测,udpSocket:didReceiveData:......被激发两次怎么一回事,因为在第一次发送者是IPv6地址,第二次发送者是IPv4的地址相同的地址.
所以我的解决方案是只启用UDP套接字中的IPv4:
[udpSocket setIPv4Enabled:YES];
[udpSocket setIPv6Enabled:NO];
Run Code Online (Sandbox Code Playgroud)
响应消息和请求消息所包含的内容是否相同?如果是,那么您可能会遇到以下一种情况。可能第一个数据包是您正在监听的广播,第二个数据包是响应。更准确地说,当你发送广播(pkt p1)时,那么发送者也可以获得p1的副本。接下来,当接收方发送响应 (pkt p2) 时,您也会看到响应。
那么,我们如何验证呢。你可以查看发件人的地址(UDP提供了一个选项),然后检查它是你的地址还是对方主机的地址。