All,
I have a server that has a tcp socket stream for communication. I need to get to that stream and read the initial data that it needs to send me.
My cur
I came up with this, based on some other answers.
public enum StreamError: Error {
case Error(error: Error?, partialData: [UInt8])
}
extension InputStream {
public func readData(bufferSize: Int = 1024) throws -> Data {
var buffer = [UInt8](repeating: 0, count: bufferSize)
var data: [UInt8] = []
open()
while true {
let count = read(&buffer, maxLength: buffer.capacity)
guard count >= 0 else {
close()
throw StreamError.Error(error: streamError, partialData: data)
}
guard count != 0 else {
close()
return Data(bytes: data)
}
data.append(contentsOf: (buffer.prefix(count)))
}
}
}