【问题标题】:L2CAP channel, bytes sent but not arrivingL2CAP 通道,已发送但未到达的字节
【发布时间】:2020-01-06 00:55:04
【问题描述】:

在 iOS 应用程序中,我正在使用 CoreBlueTooth L2CAP channel 在一台设备和另一台设备之间进行音频文件传输。它已经工作了一半,但还没有完全工作。至此我已经转移了文件名,但是来到文件内容,是这种情况。

在发送端,所有字节都被发送(几十万字节),分布在几个块中。但在接收端,似乎只有前几千个字节到达目的地。

功能:

func stream(_ aStream: Stream,
            handle eventCode: Stream.Event) {
    ......
}

被调用一次(使用 Stream.Event.hasBytesAvailable)并获取前几千个字节。但后来它再也没有被调用过。这可能是什么原因?我希望在收到所有字节之前尽可能多次调用它。

【问题讨论】:

  • 请出示您的发送代码。收到一些字节后,您应该检查流上的hasBytesAvailable,如果仍有可用字节,请再次调用read。您不能依赖被调用的事件处理程序。在 largedata 分支中检查我更新的外围代码

标签: ios swift core-bluetooth l2cap


【解决方案1】:

完成read 后,您需要检查流的hasBytesAvailable 属性,如果为真,则发出另一个read。可能不会调用事件处理程序。

例如:

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")
        self.readBytes(from: aStream as! InputStream)
    case Stream.Event.hasSpaceAvailable:
        print("Space is available")
    case Stream.Event.errorOccurred:
        print("Stream error")
    default:
        print("Unknown stream event")
    }
}

func readBytes(from stream: InputStream) {
    let bufLength = 1024
    let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufLength)
    let bytesRead = stream.read(buffer, maxLength: bufLength)
    print("bytesRead = \(bytesRead)")
    self.bytesReceived += bytesRead
    if stream.hasBytesAvailable {
        self.readBytes(from: stream)
    }
}

【讨论】:

  • 好的。我不知道必须运行这个: if stream.hasBytesAvailable { self.readBytes(from: stream) } 我认为流函数被自动调用并完成了所有操作。我会试试的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
相关资源
最近更新 更多