直接流式方法CopyTo找不到结尾

时间:2018-12-12 10:09:45

标签: vb.net stream server-sent-events

我正在使用此方法阅读SSE

    Public Shared Sub ReadStreamForever(ByVal stream As Stream)
    Dim encoder = New UTF8Encoding()
    Dim buffer = New Byte(2047) {}
    Dim counter As Integer = 0
    While True
        If stream.CanRead Then
            Dim len As Integer = stream.Read(buffer, 0, 2048)
            counter = counter + 1
            If len > 0 Then
                Dim text = encoder.GetString(buffer, 0, len)
                SSEApplication.Push(text) 'Here I collect the text slices to a List(of string) object
            Else
                Exit While
            End If
        Else
            Exit While
        End If
    End While
    SSEApplication.writer() 'Here I write the content to a .txt file
End Sub

使用我的示例数据,大约需要2秒钟。我宁愿不要将流读入内存并尝试这种方法

Public Shared Sub ReadStreamForever1(ByVal stream As Stream)

    Dim output As FileStream = File.OpenWrite("C:\Users\mini_dataset.txt")
    While True
        If stream.CanRead Then
            stream.CopyTo(output)
        Else
            Exit While
        End If
    End While
End Sub

但是该过程最终以一个无限循环结束(我想),至少对我来说,它似乎找不到流的末尾。几秒钟后,我可以中断该过程,所有数据都位于.txt文件中。知道我该怎么做才能使直接流到文件方法正常工作吗?

1 个答案:

答案 0 :(得分:2)

Stream.CanRead告诉您流是否支持阅读。由于显然可读,While True将永远存在。
让我们验证是否改为输出Stream.CanWrite

Public Shared Sub ReadStreamForever1(ByVal stream As Stream)
    Using output As FileStream = File.OpenWrite("[Output file path]")
        If output.CanWrite Then
            stream.CopyTo(output)
        End If
    End Using
End Sub

如果该过程花费一些时间,并且您需要报告其进度,则可以read the stream using a buffer(我没有添加任何错误检查,但是当然应该使用try / catch块):
(在这里,ProgressBar通常使用100个分区)

Public Sub ReadStreamForever1(ByVal stream As Stream)
    Dim BufferLength As Integer = 81920 'As the default stream buffer
    Dim Buffer(BufferLength) As Byte
    Dim BytesRead As Long = 0L

    Using output As FileStream = File.OpenWrite("[Output file path]")
        If output.CanWrite Then
            Dim Part As Long = stream.Length \ 100
            Dim PartCount As Integer = 0
            Dim read As Integer = 0
            Do
                read = stream.Read(Buffer, 0, BufferLength)
                If read = 0 Then Exit Do
                If (BytesRead / Part > PartCount) Then
                    PartCount += 1
                    'ReportWriteProgress(PartCount)
                End If
                output.Write(Buffer, 0, read)
                BytesRead += read
            Loop
        End If
    End Using
End Sub