使用 CoreFoundation 发布 UDP 数据包的流程

Flow of posting UDP packet with CoreFoundation

我正在编写使用 CoreFoundation 发送 UDP 数据包的代码。这是代码

CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP, 0u, NULL, NULL);
// ... (handle error if socket is NULL)

struct sockaddr_in sockaddr;
// ... (set fields of sockaddr)
NSData *addressData = [NSData dataWithBytes: &sockaddr length: sockaddr.sin_len];

if (CFSocketSendData(self.socket, (__bridge CFDataRef) addressData, (__bridge CFDataRef) data, 0) != kCFSocketSuccess) {
    // ... (handle error)
}

但是,我不确定如何完成这个流程,即我有以下问题:

谢谢。

Should I close / release the socket somehow if I am not going to send more data? If so, is CFSocketInvalidate the appropriate function?

是的。调用 CFSocketInvalidate,然后调用 CFRelease

Can I invalidate the socket right after calling CFSocketSendData or should I wait until the data are send?

source code 中,CFSocketSendData 调用 sendto 并设置了 SO_SNDTIMEO 选项。

无需等待。如果CFSocketSendDatareturnskCFSocketSuccess,你就大功告成了。

请注意,对于 TCP 连接,这种情况可能 more complicated

However, can I detect some errors which occur on my side during sending?

可以。使用 errno。列出了 sendto 的可能错误 here