您只需要记下发送了多少字符,从data
实例中删除这些字符,然后当您收到指示输出流中有可用空间的委托回调时,再发送一些。
例如,您可以添加几个属性来保存排队的数据和一个串行调度队列,以确保对该队列的线程安全访问:
private var queueQueue = DispatchQueue(label: "queue queue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem, target: nil)
private var outputData = Data()
现在,在sendTextTapped
函数中,您只需将新数据添加到输出队列:
@IBAction func sendTextTapped(_ sender: UIButton) {
var lngStr = "1234567890"
for _ in 1...10 {lngStr = lngStr + lngStr}
let data = lngStr.data(using: .utf8)!
self.queue(data:data)
}
该函数以线程安全的方式queue(data:)
将数据添加到对象并调用outputData
send()
private func queue(data: Data) {
queueQueue.sync {
self.outputData.append(data)
}
self.send()
}
send()
确保流已连接,有数据要发送并且输出流中有可用空间。如果一切正常,那么它会发送尽可能多的字节。然后从输出中删除发送的字节data
(再次以线程安全的方式)。
private func send() {
guard let ostream = self.channel?.outputStream, !self.outputData.isEmpty, ostream.hasSpaceAvailable else{
return
}
let bytesWritten = outputData.withUnsafeBytes { ostream.write($0, maxLength: self.outputData.count) }
print("bytesWritten = \(bytesWritten)")
queueQueue.sync {
if bytesWritten < outputData.count {
outputData = outputData.advanced(by: bytesWritten)
} else {
outputData.removeAll()
}
}
}
最后的更改是调用send()
以响应.hasSpaceAvailable
流事件:
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event.openCompleted:
print("Stream is open")
case Stream.Event.endEncountered:
print("End Encountered")
case Stream.Event.hasBytesAvailable:
print("Bytes are available")
case Stream.Event.hasSpaceAvailable:
print("Space is available")
self.send()
case Stream.Event.errorOccurred:
print("Stream error")
default:
print("Unknown stream event")
}
}
您可以在示例的largedata分支中看到修改后的代码