why GCDAsyncUdpSocket cannot send/receive packets after a while in broadcast mode?


Answers

Question

I am using GCDAsyncUdpSocket to write a UDP socket in my app. The scenario is like this: when users click the button, it will send a broadcast packet in LAN then listen to the response, there is a server in LAN which will respond with one UDP packet. When the app receives the response, it will do something.

I set GCDAsyncUdpSocket as followings:

- (void)setupSocket
{
    _udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *error = nil;

    if (![_udpSocket bindToPort:18686 error:&error]) {
        NSLog(@"Error binding: %@",error);
        return;
    }

    if (![_udpSocket beginReceiving:&error]) {
        NSLog(@"Error receiving: %@",error);
        return;
    }

    if (![_udpSocket enableBroadcast:YES error:&error]) {
        NSLog(@"Error enableBroadcast: %@",error);
        return;
    } 
}

then i send Packet in button action as following:

NSString *host = @"255.255.255.255";
int port = 8585;
NSString *msg = @"Hello from iOS";
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[_udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0]; 

in

- (void)udpSocket:(GCDAsyncUdpSocket *)sock     didReceiveData:(NSData *)data
                                                fromAddress:(NSData *)address
                                                withFilterContext:(id)filterContext

method i listen the port to do somethings. It works perfectly at beginning, but if you try to click the button later (about 1 hour), then it cannot send UDP packet any more.

My server in LAN will print the data received. I thought there was something wrong with send method. so i use BSD socket methods to send The data. and use GCDAsyncUdpSocket to receive the response. but the same thing happened after a while. this time i can send but cannot receive.

Am i missing something about GCDAsyncUdpSocket? why it cannot send/receive after a while? Any help would be much appreciated.





Tags