问题
I have set up some data transfer function, using CoreBluetooth
CBL2CAPChannel
, in a Swift
iOS
app. Here is the function for sending data:
func sendData(_ outStream: OutputStream) -> Bool {
let data = tranferBlock! // tranferBlock holds some .utf8 data.
let bytesWritten = data.withUnsafeBytes {outStream.write($0, maxLength: data.count)}
if bytesWritten > 0 {
tranferBlock = nil
return true
}
return false
}
And here is the function for receiving data:
func receiveData(_ inStream: InputStream) {
let bufLength = 1024
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufLength)
let bytesRead = inStream.read(buffer, maxLength: bufLength)
if let string = String(bytesNoCopy: buffer,
length: bytesRead,
encoding: .utf8,
freeWhenDone: false) {
print("READ-L2CAPData:\(bytesRead):\(string)")
if bytesRead != 0 {
receiveBuffer = string // receiveBuffer holds the received data.
let ntfc = NotificationCenter.default
ntfc.post(name:Notification.Name(rawValue: "DATACAMEIN"),
object: nil, userInfo: nil)
}
}
}
I can say, it is working, because this allows me to transfer data. But there is one issue: I do not receive data the same way I send it. For example, let us say I send data in 3 packets, like this:
.......
tranferBlock = Data("aaaAAAaaa".utf8)
sendData(outStream)
tranferBlock = Data("bbbBBBbbb".utf8)
sendData(outStream)
tranferBlock = Data("cccCCCccc".utf8)
sendData(outStream)
.......
I would expect, in that case to receive the data in 3 packets, at about the same pace I have sent them:
aaaAAAaaa
bbbBBBbbb
cccCCCccc
But instead I receive one packet:
aaaAAAaaabbbBBBbbbcccCCCccc
And very often, for some reason that I do not know, only when I kill the sending app.
I would like to know what I need to change to receive the data the way I expect.
来源:https://stackoverflow.com/questions/57635965/using-corebluetooth-cbl2capchannel-to-move-data