Swift范围超出数据长度

2024-06-28 11:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python服务器,使用流委托进行写和读。它工作得很好,但当我开始一个匹配,服务器发回数据时,它崩溃了。在

这里是它崩溃的地方:

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)
        }
    }
}

设置“let message”时崩溃。在

我尝试过一些方法,比如试图搞乱范围本身,但我不太清楚它为什么会这样做,如果需要,我可以发布用于发送消息的服务器代码。在


Tags: 服务器messagereturnifbytesherebufferlength