0

我一直在尝试使用Kitura BlueSocket通过 TCP 发送图像。

每次我尝试从 Data 对象解码图像时,我都会得到

警告![0x7fb6f205e400] 解码不完整,错误代码为 -1。如果图像尚未完全下载,这是预期的。

事实上,图像通常是半载的。这是我用于下载数据对象的代码:

func readData() -> Data {
        var receivedData = Data.init()

        do {
            try mySocket?.read(into: &receivedData)
        }
        catch {
            print("Error receiving data")
        }
        return receivedData
}

这就是我解码图像的方式:

func decodeImage(from: Data){
    imageRead.image = UIImage(data: from)
}

并且此代码在 View Controller 中使用,如下所示:

let imageData = networkManager.readData()
decodeImage(from: imageData)

我不知道为什么图像没有完全下载。

4

1 回答 1

0

You're working with a low-level socket. TCP just knows about packets; it doesn't know anything about "images" or "records" or anything else. It just deals with packets. Depending on various factors, you may see packets as small as a few hundred bytes to as large as a few kB.

.read(into:) returns you whatever packets have arrived so far. It doesn't know where the boundaries of your image are. That's up to you to determine. You need to loop until all the data you want to process has arrived (what that means completely depends on the protocol you've designed). You can't run this on the main queue; it'll block your UI. It needs to run on a background queue.

A very common socket-level protocol is to send the length first, and then send the data. That way the reader knows how much data to expect, and will know when the transfer is done. If the sender doesn't know the size when it starts transmitting, then you would typically use an "end-of-transfer" token of some sort, or use a protocol that chunks the data into blocks, and then has some marker to note "this is the last block." But in any case, you'll need to choose or design a protocol you want to use here. (Or use an existing system like HTTP rather than a low-level socket.)

于 2021-02-18T15:58:10.910 回答