使用 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)
}
但是,我不确定如何完成这个流程,即我有以下问题:
- 如果我不打算发送更多数据,是否应该以某种方式关闭/释放套接字?如果是这样,
CFSocketInvalidate
是合适的函数吗?
CFSocketSendData
的文档说:"If this function returns kCFSocketSuccess, then by the time it returns, the data has been queued in the socket buffer for delivery." 我可以在调用后立即使套接字无效 CFSocketSendData
还是应该等到数据发送完毕?
- 如果需要等待,如何知道数据已经发送?我能查出是否有错误吗? (当然,我不能保证接收方通过UDP获取数据。但是,我可以检测到发送过程中我这边出现的一些错误吗?)
谢谢。
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
选项。
无需等待。如果CFSocketSendData
returnskCFSocketSuccess
,你就大功告成了。
请注意,对于 TCP 连接,这种情况可能 more complicated。
However, can I detect some errors which occur on my side during sending?
可以。使用 errno
。列出了 sendto
的可能错误 here。
我正在编写使用 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)
}
但是,我不确定如何完成这个流程,即我有以下问题:
- 如果我不打算发送更多数据,是否应该以某种方式关闭/释放套接字?如果是这样,
CFSocketInvalidate
是合适的函数吗? CFSocketSendData
的文档说:"If this function returns kCFSocketSuccess, then by the time it returns, the data has been queued in the socket buffer for delivery." 我可以在调用后立即使套接字无效CFSocketSendData
还是应该等到数据发送完毕?- 如果需要等待,如何知道数据已经发送?我能查出是否有错误吗? (当然,我不能保证接收方通过UDP获取数据。但是,我可以检测到发送过程中我这边出现的一些错误吗?)
谢谢。
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
选项。
无需等待。如果CFSocketSendData
returnskCFSocketSuccess
,你就大功告成了。
请注意,对于 TCP 连接,这种情况可能 more complicated。
However, can I detect some errors which occur on my side during sending?
可以。使用 errno
。列出了 sendto
的可能错误 here。