我PushStreamContent
在 ASP.NET Web API 中使用将事件从服务器推送到客户端(使用服务器发送事件)。在每个发送的事件之后,我调用Flush
将Stream
缓冲的数据推送到客户端。但是,我注意到冲洗不会(总是)发生。有时,部分数据会发送到客户端,其余的会在写入下一个事件时发送(可能会在几秒钟后发生)。
这是一个代码示例:
public class MyController : ApiController
{
private static readonly string[] LineSeparators
= new[] { Environment.NewLine };
public HttpResponseMessage GetData(string id)
{
var response = Request.CreateResponse();
response.Content = new PushStreamContent(
new Func<Stream, HttpContent, TransportContext, Task>(StartStream),
new MediaTypeHeaderValue("text/event-stream") { CharSet = "UTF-8" });
return response;
}
private async Task StartStream(Stream outputStream, HttpContent content, TransportContext context)
{
using (outputStream)
using (var writer = new StreamWriter(outputStream, new UTF8Encoding(false)))
{
writer.NewLine = "\n";
while (true)
{
WriteEvent(writer, "ping", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture));
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
}
private static void WriteEvent(TextWriter writer, string eventType, string data)
{
writer.WriteLine("event:" + eventType);
writer.WriteLine("data:" + data);
writer.WriteLine();
writer.Flush(); // StreamWriter.Flush calls Flush on underlying Stream
}
}
如何禁用数据缓冲或强制刷新数据?