This answer和this 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)))
真正的问题是从CFDataRef
(myWriteStream
)获取NSOutputStream
,然后从中获取CFSocketNativeHandle
。在上面的Swift
代码中,在尝试创建nativeSocket
时(特别是尝试访问data
属性),它始终在第一行崩溃。
有人可以帮我解决这个问题吗?
答案 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)