socket服务器:允许重用本地地址

创建本地服务器的时候,有时候会遇到这样的错误 CFSocketSetAddress bind failure: 48.
这是因为本地地址没有设置为允许重用。使用以下代码可解决这个问题;

// 设置本地地址可重用:避免调试时重启app创建CFSocketSetAddress报错:48
    UInt32 reused = 1;
    int result = setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, &reused, sizeof(reused));
    if (0 == result)
    {
        NSLog(@"[%@ %@]: Successfully allow local addreess reuse.", [self class], NSStringFromSelector(_cmd));
    } else
    {
        NSLog(@"[%@ %@]: Fail to allow loacl addreess reuse.", [self class], NSStringFromSelector(_cmd));
    }

注意: 如果把UInt32 reused = 1; 该成BOOL reused = YES;则会设置失败。

你可能感兴趣的:(socket服务器:允许重用本地地址)