在使用 EventStream POST API 时,可以通过监听数据流的结束标记 ('\r\n\r\n') 来判断数据接收完成。当接收到结束标记时,可以退出接收并处理接收到的数据。以下是一个示例代码:

using System.IO;
using System.Net;
using System.Text;

class EventStreamClient
{
    public void PostEventStream()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://example.com/api");
        request.Method = "POST";
        request.ContentType = "text/event-stream";
        request.Timeout = Timeout.Infinite;

        // Send the request asynchronously.
        using (var stream = request.GetRequestStream())
        {
            // Write the data to the request stream.
            byte[] data = Encoding.UTF8.GetBytes("data: Hello, World!\n\n");
            stream.Write(data, 0, data.Length);
        }

        // Receive the response asynchronously.
        using (var response = request.GetResponse())
        using (var stream = response.GetResponseStream())
        using (var reader = new StreamReader(stream))
        {
            while (true)
            {
                // Read the next line from the response stream.
                string line = reader.ReadLine();

                if (line == null)
                {
                    // The connection was closed.
                    break;
                }
                else if (line == "\r\n")
                {
                    // The current event is complete.
                    // TODO: Process the event data.
                }
            }
        }
    }
}

在上面的示例中,我们使用了一个无限超时时间来保持连接打开并持续接收数据。当读取到空行 ('\r\n') 时,我们认为当前事件已经接收完毕,可以退出接收并处理接收到的数据。如果读取到的行为 null,则表示连接已经被关闭,可以退出接收。

C# .NET 4.5.1 EventStream POST API 数据接收完成判断及退出

原文地址: https://www.cveoy.top/t/topic/mxX0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录