使用Web API流式传输MJPEG缓冲区

问题描述 投票:0回答:2

我正在使用HttpSelfHostConfiguration来创建WebAPI(服务)。我的目标是让一个路由流来自安全源的mjpeg视频,并有其他路由可用于配置和Web界面。

我遇到的问题是我遇到的每个例子都需要一个已知数量的图像才能设置主响应的内容长度。我没有这个,冲洗流不会做任何事情。

这是响应的当前代码。如果我使用相同的代码与原始套接字而不是通过ApiController,我可以很好地流式传输,但是从头开始创建一个网络服务器,我需要的其他东西看起来并不是很有趣。

[HttpGet]
public HttpResponseMessage Stream(int channel)
{
    var response = Request.CreateResponse();
    response.Content = new PushStreamContent((outputStream, content, context) =>
    {
        StreamWriter writer = new StreamWriter(outputStream);
        while (true)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ReadMemoryMappedFile(channel);

                ms.SetLength(0);
                this.Image.Bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] buffer = ms.GetBuffer();


                writer.WriteLine("--boundary");
                writer.WriteLine("Content-Type: image/jpeg");
                writer.WriteLine(string.Format("Content-length: {0}", buffer.Length));
                writer.WriteLine();
                writer.Write(buffer);

                writer.Flush();
            }
        }
    });
    response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/x-mixed-replace; boundary=--boundary");
    return response;
}
asp.net-web-api mjpeg
2个回答
0
投票

我无法找到明确说明这一点的任何地方,但我会假设HttpSelfHostConfiguration不支持我正在寻找的功能,并且总是要求在释放缓冲区之前关闭流。

我用HWIN.SelfHost交换了HttpSelfHostConfiguration,它按预期工作。


0
投票

我希望我迟到的回答会有所帮助,因为我最近遇到了同样的问题,我花了一些时间才弄清楚...

我的解决方案是在内容类型中指定边界而不使用“ - ”(但是您需要在流中写入时保留它们)。

尝试像这样配置标头:

response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/x-mixed-replace; boundary=boundary");

并在流中写入边界:

writer.WriteLine("--boundary");

像这样它对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.