I'm using NetService to connect to iostreams of one ios device to another and I'm using the streams to send/receive data between the two ios devices. But the data transfer sometimes stops suddenly without any error and after a few minutes it gives the error "Operation timed out. Socket is not connected". This happens rarely but it does happen and I've looked around but did not find any solution related to this.
Here is the code for write method.
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
Here is the code for read method.
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 is Data property of the class where I have this read method.