1

I'm successfully using the following code to send a UDP-message to a server:

GCDAsyncUdpSocket *udpSocket; 
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSData *data = [@"initialize" dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:@"127.0.0.1" port:5000 withTimeout:-1 tag:1]; 

When the server receives this message it replies with a series of responses. How can I catch and process those? I want my app to listen to server-responses on the same port it sent the outgoing message for 2 minutes and then repeat the initialize-message in an endless loop:

message -> listen -> message -> listen ...
tshepang
  • 12,111
  • 21
  • 91
  • 136
user915245
  • 123
  • 2
  • 8
  • Maybe check out these questions on stack overflow. They mention [CocoaAsyncSocket](https://github.com/robbiehanson/CocoaAsyncSocket). - [Receive UDP packets ios](http://stackoverflow.com/questions/9674450/recieve-udp-broadcast-packets-ios) - [IPhone UDP broadcast and response](http://stackoverflow.com/questions/7630784/iphone-udp-broadcast-and-response) – PKeno Nov 08 '12 at 16:04

1 Answers1

1

I was able to figure it out myself - was not to hard after all :-)

To start listening in the background I simply used this:

NSError *error = nil;

    if (![udpSocket bindToPort:0 error:&error])
    {
        NSLog(@"Error binding: %@", [error description]);
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", [error description]);
        return;
    }

To repeatetly send the initialiszation I used a timer initlilzieServer containes the code above):

timer = [NSTimer scheduledTimerWithTimeInterval:150
                                         target:self
                                         selector:@selector(initializeServer)
                                         userInfo:nil
                                         repeats:YES];

And then I do the processing of the responses in this class:

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
NSString *msg = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if (msg)
    {
        NSLog(@"%@",msg);

    }
    else
    {
        NSString *host = nil;
        uint16_t port = 0;
        [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];

        NSLog(@"Unknown Message: %@:%hu", host, port);
    }
}
user915245
  • 123
  • 2
  • 8
  • Can you plz share your code , i got stuck in same problem .. i am able to send the packet but not getting response back from server ... – AKSH Mar 03 '16 at 12:46