gpt4 book ai didi

ios - GCDAsyncUdpSocket, "Cannot bind socket more than once"

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:42:20 27 4
gpt4 key购买 nike

我正在使用 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)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;

}

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

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

FKY

最佳答案

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com