Funkycochise
Funkycochise

Reputation: 123

GCDAsyncUdpSocket, "Cannot bind socket more than once"

I'm using GCDAsyncUdpSocket to get udp broadcast between iphone and remote udp server. I'm sending a small "hello" on a specif port to "255.255.255.255" broadcast address.

Then the server replies, allowing me to discover its ip address.

Everything works fine, especially using the simulator, except that if I run it once on the iphone, when i try to stop the app and run it right away after, I get a "Cannot bind socket more than once" error. This happens when I click stop in xcode or when I kill the app in IOS.

Here is a sample of my code :

#import "GCDAsyncUdpSocket.h"

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (udpSocket == nil)
    {
        [self setupSocket];
    }
}

- (void)setupSocket
{

    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [udpSocket enableBroadcast:YES error:nil];


    NSData *data = [@"hello" dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:data toHost:@"255.255.255.255" port:21180 withTimeout:-1 tag:tag++];

    NSError *error = nil;

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

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
      fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (msg)
    {
        [self logMessage:FORMAT(@"RECV: %@", msg)];
    }
    else
    {
        NSString *host = nil;
        uint16_t port = 0;
        [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];

        [self logInfo:FORMAT(@"RECV: Unknown message from: %@:%hu", host, port)];
    }
    [udpSocket close];
    udpSocket = NIL;

}

In fact it seems that socket reference is still binded, ignoring close action and setting to nil.

Any advice is welcome, Thanks for reading.

FKY

Upvotes: 2

Views: 2526

Answers (1)

user207421
user207421

Reputation: 310883

The socket is bound automatically when you call send. So trying to bind it again afterwards is too late. You normally don't need to bid a UDP socket at all, unless you have a fixed port number requirement, which you don't have here. Just remove it.

Upvotes: 1

Related Questions