在Swift

时间:2016-01-06 00:08:27

标签: objective-c swift cocoa networking nsstream

This answerthis answer都显示如何在TCP_NODELAY中为NSOutputStream设置Objective-C。我需要一些帮助才能在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)))

真正的问题是从CFDataRefmyWriteStream)获取NSOutputStream,然后从中获取CFSocketNativeHandle。在上面的Swift代码中,在尝试创建nativeSocket时(特别是尝试访问data属性),它始终在第一行崩溃。

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

1 个答案:

答案 0 :(得分:2)

好的,过了一会儿我发现了。以下是其他人需要的工作代码:

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)