Stream to Get Data - NSInputStream

前端 未结 2 2065
一生所求
一生所求 2020-12-30 16:10

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

2条回答
  •  自闭症患者
    2020-12-30 16:36

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

提交回复
热议问题