在 Swift 中为 NSOutputStream 设置 TCP_NODELAY

Setting TCP_NODELAY for NSOutputStream in Swift

This answer and this answer 都显示了如何在 Objective-C 中为 NSOutputStream 设置 TCP_NODELAY。我需要一些帮助才能使它在 Swift 中运行,我相信这可能只是我在 API.

中犯的一个错误

这是据称可行的 Objective-C 解决方案:

CFDataRef nativeSocket = CFWriteStreamCopyProperty(`myWriteStream`, kCFStreamPropertySocketNativeHandle);
CFSocketNativeHandle *sock = (CFSocketNativeHandle *)CFDataGetBytePtr(nativeSocket);
setsockopt(*sock, IPPROTO_TCP, TCP_NODELAY, &(int){ 1 }, sizeof(int));
CFRelease(nativeSocket);

这是我尝试将其翻译成 Swift:

let nativeSocket: CFDataRef = CFWriteStreamCopyProperty(myWriteStream, kCFStreamPropertySocketNativeHandle).data
let sock = CFSocketNativeHandle(CFDataGetBytePtr(nativeSocket).memory)
var one = Int(1)
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &one, UInt32(sizeofValue(one)))

真正的问题是从 myWriteStreamNSOutputStream)获取 CFDataRef,然后从中获取 CFSocketNativeHandle。在上面的 Swift 代码中,它总是在尝试创建 nativeSocket 时在第一行崩溃(具体来说,试图访问 data 属性)。

有人可以帮我解决这个问题吗?

好的,过了一会儿我明白了。这是工作代码,以防其他人需要它:

let socketData = CFWriteStreamCopyProperty(self.outputStream!, kCFStreamPropertySocketNativeHandle) as! CFData
let handle = CFSocketNativeHandle(CFDataGetBytePtr(socketData).memory)
var one: Int = 1
let size = UInt32(sizeofValue(one))
setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, &one, size)