gpt4 book ai didi

objective-c - 是否可以使用 GCD 调度源在套接字上执行异步连接()?

转载 作者:太空狗 更新时间:2023-10-30 03:26:40 24 4
gpt4 key购买 nike

您可以使用 GCD 调度源从套接字读取和写入,监视传入连接的监听套接字,但我不知道如何也使用调度源连接套接字?

在伪代码中,它看起来像这样:

dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, connectingSocket, ...);
dispatch_source_set_event_handler(source, ^{
// Socket did connect or not
});
fcntl(connectingSocket, F_SETFL, O_NONBLOCK);
connect(connectingSocket, addr, len);
dispatch_source_resume(source);

这比必须使用 select() 更好。

最佳答案

我最初错误地分析了您的问题...抱歉。我现在明白了...您想从 connect 获取 EINPROGRESS 并让调度源在 connect 调用需要注意时通知您,而不是使用 select 轮询...这很容易破解,而且似乎有效:

#import <sys/types.h>
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>

@implementation AppDelegate
{
dispatch_source_t foo;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

int socketFD = socket(PF_INET, SOCK_STREAM, 0);
if (socketFD == -1)
{
socketFD = -1;
abort();
}

int flags = fcntl(socketFD, F_GETFL, 0);
int status = fcntl(socketFD, F_SETFL, flags | O_NONBLOCK);
if (status == -1)
{
close(socketFD);
socketFD = -1;
abort();
}

struct sockaddr_in sockaddr4 = {0};
sockaddr4.sin_len = sizeof(sockaddr4);
sockaddr4.sin_family = AF_INET;
sockaddr4.sin_port = htons(22);
inet_aton("127.0.0.1", &sockaddr4.sin_addr);

foo = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socketFD, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(foo, ^{
if (connect(socketFD, (const struct sockaddr *)&sockaddr4, (socklen_t)sizeof(sockaddr4)))
{
int err = errno;
NSLog(@"errno: %s", strerror(err));
if (err == ECONNREFUSED)
{
abort();
}
else if (err == EISCONN)
{
// connected -- queue up other work
DoStuff();

// Cancel the source so it doesnt keep notifying...
dispatch_source_cancel(foo);
}
}
});

dispatch_source_set_cancel_handler(foo, ^{
NSLog(@"Cancel");
});

dispatch_resume(foo);

// Do initial connect
if (connect(socketFD, (const struct sockaddr *)&sockaddr4, (socklen_t)sizeof(sockaddr4)))
{
if(errno != EINPROGRESS)
{
close(socketFD);
socketFD = -1;
abort();
}
}
}

@end

关于objective-c - 是否可以使用 GCD 调度源在套接字上执行异步连接()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26388904/

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