Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios InputStream.read有时会停止读取_Ios_Swift_Inputstream_Download - Fatal编程技术网

Ios InputStream.read有时会停止读取

Ios InputStream.read有时会停止读取,ios,swift,inputstream,download,Ios,Swift,Inputstream,Download,我的应用程序应该能够使用Stream类从服务器接收消息 我的代码是: var inputStream : InputStream? = nil var outputStream : OutputStream? = nil ... func establishConnection() { ... Stream.getStreamsToHost(withName: "app.mybusiness.com", port: port, inputStream: &self.

我的应用程序应该能够使用Stream类从服务器接收消息

我的代码是:

var inputStream  : InputStream? = nil
var outputStream : OutputStream? = nil

...

func establishConnection() {
    ...
    Stream.getStreamsToHost(withName: "app.mybusiness.com", port: port, inputStream: &self.inputStream, outputStream: &self.outputStream)
    ...
}

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

    switch eventCode {
        case Stream.Event.hasBytesAvailable:
        var output = ""

        var buffer = [UInt8](repeating: 0, count: 1024)

        while (self.inputStream!.hasBytesAvailable){

            let bytesRead:Int=inputStream!.read(&buffer, maxLength: buffer.count)

            if (bytesRead > 0) { // had here (bytesRead >= 0) too
                output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding:String.Encoding.utf8.rawValue)! as String
            } else {
                print("# error")
            }
            print("> \(output)")
        }

        // Now do something with the data we got
        HelpMethods.pushServerIncoming(inString: output)

       default:
           ...
    }

}
因此,这种方法非常有效,但有时似乎会停止接收数据。
它先读取前1024个字节,然后读取第二个1024个字节,而不是继续(需要大约3或4次迭代才能获得整个消息),它只读取几个字节,然后inputStream.hasBytesAvailable返回false

很容易说:啊,这是服务器的故障,但这个问题在android版本的应用程序中不会发生

我尝试更改缓冲区大小(从1更改为4096),但没有任何改变。对于4096字节,我有一个例子,在第一次运行时,流只读取几百字节,然后说:全部完成,伙计!没什么要读的了

这种行为是不可预测的。用同一条消息测试了很多次,它工作了,工作了,工作了,没有工作


有什么建议吗?

不要检查事件处理程序中是否有更多数据可用。读取字节,处理它,然后等待另一个事件。你是否以某种方式解决了这个问题?我们面临着完全相同的问题。我认为这是我们所做的一个变通办法。首先,我们将buffersize设置为1MB。然后我使用一个字符串变量来保护传入的字节。我们收到的所有消息都有不同的格式。因此,我检查它是否是一个有效的消息(begin和end),并删除String-var。如果只有begin是有效的,我就等待是否还有其他消息。如果新字节不是消息的开头,则追加;如果是有效的消息开头,则覆盖字符串var。因此,我可能会丢失一条消息,但没有更多的崩溃(据我所知),到目前为止,我没有丢失任何消息。但这并不能保证。只是权宜之计。