Swift范围超出数据长度

时间:2018-01-30 04:04:19

标签: python swift inputstream nsrange

我有一个python服务器,我使用stream delegate编写和读取。它运行正常但是当我开始匹配并且服务器发回数据时它崩溃了。

这里崩溃的地方:

func checkForMessages() {
    while true {
        if inputBuffer.length < 4 {
            print("buffer length\(inputBuffer.length)")
            print( MemoryLayout.size(ofValue: Int()))
            print("application quit here")
            return
        }
        var msgLength = (inputBuffer.bytes).load(as: UInt32.self)
        msgLength = UInt32(bigEndian: msgLength)
        print(inputBuffer.length)
        print(msgLength)
        if inputBuffer.length < msgLength {
            print("its returning here!")
            return
        }

        // ******Crashes on the line Below******

        let message: Data? = inputBuffer.subdata(with: NSRange(location: 4, length: Int(msgLength)))
        processMessage(message!)
        let amtRemaining: Int = inputBuffer.length - Int(msgLength) - 4
        if amtRemaining == 0 {
            inputBuffer = NSMutableData()
        }
        else {
            print("Creating input buffer of length \(amtRemaining)")
            inputBuffer = NSMutableData(bytes: inputBuffer.bytes + 4 + Int(msgLength), length: amtRemaining)
        }
    }
}

设置&#34;让消息&#34;。

时崩溃

我尝试了一些事情,比如试图弄乱范围本身,但我不太确定为什么它做它做的事情,我可以发布用于发送消息的服务器代码,如果需要的话。

1 个答案:

答案 0 :(得分:0)

因此,通过替换代码的以下部分来解决问题:

 if inputBuffer.length < msgLength {
        return
    }

 if inputBuffer.length < msgLength + 4 {
        return
    }