为NSOutputStream禁用Nagle的算法

时间:2014-05-22 14:56:15

标签: ios objective-c network-programming nsstream multipeer-connectivity

我正在使用MPCF制作多人游戏。您可以使用iPhone控制iPad上的太空飞船。

我遇到了各种滞后和延迟以及随机时间和间隔的缓冲/暂停,现在已经登陆Apples Technical Q&A NW26论文,讨论禁用Nagle算法。我尝试了,但我的程序不断崩溃,我不明白为什么。似乎CFWriteStreamCopyProperty总是返回NULL。

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
    switch (eventCode) {
        case NSStreamEventOpenCompleted:

            // Trying to get a handle to the native socket
            CFSocketNativeHandle rawsock;

            // This always return NULL
            CFDataRef socketData = CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)(stream), kCFStreamPropertySocketNativeHandle); 

            // And this row always crash (coz of socketData being NULL i guess)
            CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&rawsock); 
            CFRelease(socketData);

            // Code example from Apple that need a handle to the native socket, that I am trying to get above
            int err; 
            static const int kOne = 1;  
            err = setsockopt(rawsock, IPPROTO_TCP, TCP_NODELAY, &kOne, sizeof(kOne)); 
            if (err < 0) {     
                err = errno; 
            }

            break;

        default:
            break;
    }
}

感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

您假设streamNSOutputStream,但也可以传递NSInputStream。 所以它就崩溃了。

以下示例代码可以处理这两种情况并修复崩溃:

- (void)disableNaglesAlgorithmForStream:(NSStream *)stream {

    CFDataRef socketData;

    // Get socket data
    if ([stream isKindOfClass:[NSOutputStream class]]) {
        socketData = CFWriteStreamCopyProperty((__bridge CFWriteStreamRef)((NSOutputStream *)stream), kCFStreamPropertySocketNativeHandle);
    } else if ([stream isKindOfClass:[NSInputStream class]]) {
        socketData = CFReadStreamCopyProperty((__bridge CFReadStreamRef)((NSInputStream *)stream), kCFStreamPropertySocketNativeHandle);
    }

    // get a handle to the native socket
    CFSocketNativeHandle rawsock;

    CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&rawsock);
    CFRelease(socketData);

    // Disable Nagle's algorythm

    // Debug info
    BOOL isInput = [stream isKindOfClass:[NSInputStream class]];
    NSString * streamType = isInput ? @"INPUT" : @"OUTPUT";

    int err;
    static const int kOne = 1;
    err = setsockopt(rawsock, IPPROTO_TCP, TCP_NODELAY, &kOne, sizeof(kOne));
    if (err < 0) {
        err = errno;
        NSLog(@"Could Not Disable Nagle for %@ stream", streamType);
    } else {
        NSLog(@"Nagle Is Disabled for %@ stream", streamType);
    }
}

这应该在case NSStreamEventOpenCompleted:

中调用

对于任何想知道为什么在复制粘贴时不能编译的人:

#import <arpa/inet.h>       // for IPPROTO_TCP
#include <netinet/tcp.h>    // for TCP_NODELAY

但是,它对周期性延迟问题没有帮助。 我还在寻找防止这种情况的方法。

我录制了一个简单的视频来演示这个问题,我相信你遇到了同样的问题: https://www.dropbox.com/s/omdqkbckph4b1y2/Multipeer%20Connectivity.mov?dl=0

编辑:我找到了解决定期延迟问题的方法。导致问题的是MCNearbyServiceAdvertiser。 你需要停止宣传同伴以摆脱滞后: 在连接成功后立即在stopAdvertisingPeer实例上调用MCNearbyServiceAdvertiser方法。

MCNearbyServiceAdvertiser *nearbyServiceAdvertiser;

- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state {

    switch (state) {

        case MCSessionStateConnected: {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.nearbyServiceAdvertiser stopAdvertisingPeer];
            });
        ...
    }
    ...
}

但只有在 30秒之后,延迟才会关闭。我不知道如何让它立刻消失。