OGeek|极客世界-中国程序员成长平台

标题: ios - GCDAsyncUdpSocket, "Cannot bind socket more than once" [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:04
标题: ios - GCDAsyncUdpSocket, "Cannot bind socket more than once"

我正在使用 GCDAsyncUdpSocket 在 iphone 和远程 udp 服务器之间获取 udp 广播。 我正在特定端口上向“255.255.255.255”广播地址发送一个小的“hello”。

然后服务器回复,让我发现它的 IP 地址。

一切正常,尤其是使用模拟器,除了如果我在 iphone 上运行一次, 当我尝试停止应用程序并立即运行它时,我收到“无法多次绑定(bind)套接字”错误。当我在 xcode 中单击停止或在 IOS 中终止应用程序时会发生这种情况。

这是我的代码示例:

#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)udpSocketGCDAsyncUdpSocket *)sock didReceiveDataNSData *)data
      fromAddressNSData *)address
withFilterContextid)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;

}

实际上,套接字引用似乎仍然被绑定(bind),忽略关闭操作并设置为零。

欢迎任何建议, 感谢阅读。

FKY



Best Answer-推荐答案


当您调用 send 时,套接字会自动绑定(bind)。所以之后再尝试绑定(bind)它为时已晚。通常,您根本不需要投标 UDP 套接字,除非您有固定的端口号要求,而这里没有。只需将其删除。

关于ios - GCDAsyncUdpSocket, "Cannot bind socket more than once",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381636/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4