outputStream.write有时会停止写入数据

时间:2019-09-26 05:47:10

标签: ios swift network-programming nsinputstream nsoutputstream

我正在使用NetService将一个ios设备的iostream连接到另一个,并且正在使用流在两个ios设备之间发送/接收数据。但是,数据传输有时会突然停止而没有任何错误,并且在几分钟后出现错误“操作超时。未连接套接字”。这种情况很少发生,但是确实发生,我环顾四周,但没有找到与此相关的任何解决方案。

这是写方法的代码。

extension OutputStream {
    func write(data: Data) -> Int {

        var bytesRemaining = data.count
        var totalBytesWritten = 0
        var bytesWritten = 0

        while bytesRemaining > 0 {
                bytesWritten = data.withUnsafeBytes {
                self.write(
                    $0.advanced(by: totalBytesWritten),
                    maxLength: bytesRemaining
                )
            }


            if bytesWritten < 0 {
                return -1
            } else if bytesWritten == 0 {
                return totalBytesWritten
            }

            bytesRemaining -= bytesWritten
            totalBytesWritten += bytesWritten
       }

       return totalBytesWritten
  }//end method
}//end extension

这是读取方法的代码。

func readDataFrom2(_ aStreamP: Stream) {
    var buffer = [UInt8](repeating: 0, count: bufferSize)

    if aStreamP == self.connectedInputStream, let inputStream = self.connectedInputStream {

        while (inputStream.hasBytesAvailable){
            let len = inputStream.read(&buffer, maxLength: buffer.count)
            if(len > 0) {
                let streamedData = Data.init(bytes: buffer, count: len)
                self.readData += streamedData
            }//end if len > 0

        }//end whileLoop
    }//end if inputStream

}//end method

self.readData是我拥有此读取方法的类的Data属性。

0 个答案:

没有答案