ios在UDP中以高速读取数据
我正在使用GCDAsyncSocket(ios设备)建立UDP连接。一切正常,我能够发送和接收消息,我的问题是我想快速交换数据。我可以从iphone向pc发送非常快的数据,但我无法以这种速度从pc获取数据,更具体地说,我希望能够每100毫秒获取一次数据。 我在成功连接时使用此功能:ios在UDP中以高速读取数据,ios,udp,asyncsocket,Ios,Udp,Asyncsocket,我正在使用GCDAsyncSocket(ios设备)建立UDP连接。一切正常,我能够发送和接收消息,我的问题是我想快速交换数据。我可以从iphone向pc发送非常快的数据,但我无法以这种速度从pc获取数据,更具体地说,我希望能够每100毫秒获取一次数据。 我在成功连接时使用此功能: -(void)startRead { [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startRead) us
-(void)startRead {
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startRead) userInfo:nil repeats:YES];
[asyncSocket readDataWithTimeout:-1 tag:0];
}
有了这个,我可以以1秒的时间间隔读取数据,但是如果我尝试以0.1秒的时间间隔读取数据,我的程序就会冻结。(与1秒以下的值相同)我确信我在这里做错了什么,并且有一种方法可以实现我想要的,所以如果有人知道plz帮助!!
thanx我相信上面的评论是正确的,您没有在init上正确设置委托。套接字创建应该是这样的
GCDAsyncUdpSocket* udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket bindToPort:0 error:&error])
{
[self logError:[NSString stringWithFormat:@"Error binding: %@", error]];
return;
}
if (![udpSocket beginReceiving:&error])
{
[self logError:[NSString stringWithFormat:@"Error receiving: %@", error]];
return;
}
NSString *_host = nil;
uint16_t _port = 0;
[GCDAsyncUdpSocket getHost:&_host port:&_port fromAddress:udpSocket.localAddress];
[self logInfo:[NSString stringWithFormat:@"Socket setup on host %@:%d", _host, _port]];
[self logInfo:@"Socket created successfully."];
除非您使用的GCDAsyncUdpSocket版本与我熟悉的不同,否则正确的回调方法实际上是下面的方法。当设置委托并在正确的端口上接收到数据包时,将自动调用此函数
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
你为什么需要一个计时器?我认为GCDAsyncSocket具有完成函数,在读取数据时调用这些函数。从那里你可以开始下一个读取操作。我怎么做?我尝试只调用此[asyncSocket readDataWithTimeout:-1标记:0];当我连接但它没有调用这个-(void)socket:(GCDAsyncSocket*)sock didReadData:(NSData*)data with tag:(long)tag当我获取数据时,它只与intervalI一起工作,没有与GCDAsyncSocket一起工作,但我有一些问题:据我所知,readDataWithTimeout是用于TCP套接字的。对于UDP套接字,有receiveOnce或beginReceiving(在GCDAsyncUdpSocket.h中)。您还必须设置委托,否则将不会调用委托函数。