如何在IOS中使用UDP广播进行网络发现

时间:2017-10-25 07:49:35

标签: ios objective-c

我想在IOS中使用UDP广播进行网络发现。我不知道该怎么做。你能告诉我如何做的建议吗?

我想这样做tutorial

1 个答案:

答案 0 :(得分:4)

您可以使用Cocoa Async Socket

https://github.com/robbiehanson/CocoaAsyncSocket

以下是代码

    GCDAsyncUdpSocket *udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *error = nil;

    if (![udpSocket enableReusePort:YES error:&error]) 
    {
        return;
    }

    if (![udpSocket bindToPort:8888 error:&error])
    {
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        return;
    }

    error = nil;
    if(![udpSocket enableBroadcast:YES error:&error])
    {
    }

    NSData *data = [@"DISCOVER_FUIFSERVER_REQUEST" dataUsingEncoding:NSUTF8StringEncoding];
    [udpSocket sendData:data toHost:@“255.255.255.255” port:8888 withTimeout:10 tag:100];

以下是您将获得回复的委托方法

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
      fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
     NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

     NSString *msg1 = [NSString stringWithFormat:@"RECV: %@ FROM: %@", msg,[GCDAsyncUdpSocket hostFromAddress:address]];

    if([msg isEqualToString:@"DISCOVER_FUIFSERVER_RESPONSE"])
    {
    }
}

如果在udp套接字连接时出现错误,则会调用此委托方法

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error
{
    if (error) {
        NSString *msg = [NSString stringWithFormat:@"RECV: error: %@", [error localizedDescription]];
    }
}