流没有结束

时间:2018-12-05 13:08:28

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

我尝试使用以下代码编写一个使用服务器发送事件的客户端:

Public Shared Function OpenSSEStream(ByVal url As String, ByVal _token As String, ByVal _identifier As String, ByVal _environment As String) As Stream
    Dim request = WebRequest.Create(New Uri(url))
    CType(request, HttpWebRequest).AllowReadStreamBuffering = False
    request.Headers.Add("Authorization:Bearer " + _token)
    request.Headers.Add("environment:" + _environment)
    request.Credentials = New NetworkCredential("id", _identifier)
    Dim response = request.GetResponse()
    Dim stream = response.GetResponseStream()
    SSEApplication.ReadStreamForever(stream)
    Return stream
End Function

Public Shared Sub ReadStreamForever(ByVal stream As Stream)
    Dim encoder = New UTF8Encoding()
    Dim buffer = New Byte(2047) {}

    While True
        If stream.CanRead Then
            Dim len As Integer = stream.Read(buffer, 0, 2048)
            If len > 0 Then
                Dim text = encoder.GetString(buffer, 0, len)
            End If
        End If
    End While
End Sub

这很好用,因此,我可以在文本变量中看到来自服务器的文本(在调试模式下)。不幸的是,如果我运行代码(而不是调试),则会进入中断模式。我可以在“调试模式”下看到该文本文件充满了大约2000个数据集,并且看起来流没有结束并且陷入了无限循环?有人能帮我一下吗?

1 个答案:

答案 0 :(得分:2)

您需要退出循环,现在没有任何内容告诉它退出。

While True
    If stream.CanRead Then
        Dim len As Integer = stream.Read(buffer, 0, 2048)
        If len > 0 Then
            Dim text = encoder.GetString(buffer, 0, len)
        Else
            Exit While
        End If
    Else
        Exit While
    End If
End While

此外,流只能分段接收信息。您应该串联数据。

Dim text As String = ""

While True
    If stream.CanRead Then
        Dim len As Integer = stream.Read(buffer, 0, 2048)
        If len > 0 Then
            text &= encoder.GetString(buffer, 0, len)
        Else
            Exit While
        End If
    Else
        Exit While
    End If
End While

这都可以重构

Dim streamData As New StringBuilder

While stream.CanRead
    Dim len As Integer = stream.Read(buffer, 0, 2048)

    If len > 0 Then
        ' There is the possibility that a Unicode character be split
        streamData.Append(encoder.GetString(buffer, 0, len))
    Else
         Exit While
    End If
End While