我有一个问题,我向客户端发送 udp 消息(广播)并获得答案,但这将显示两次。当我检查我的 PC 与 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
这是输出!
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
如果有人可以帮助我,我将不胜感激。