如何使用Nancy编写MJPEG服务器

本文关键字:MJPEG 服务器 编写 Nancy 何使用 | 更新日期: 2023-09-27 18:24:07

我有以下内容:

public sealed class ServerModule : NancyModule
{
    public ServerModule()
    {
        Get["/video"] = o =>
        {
            byte[] img = GetImage("whatever.jpeg");
            return new MjpegResponse(firstImg);
        };
    }
    private sealed class MjpegResponse : Response
    {
        public MjpegResponse(byte[] data)
        {
            this.Headers.Clear();
            this.Headers.Add("Server", "IP Webcam Server 1.5");
            this.Headers.Add("Connection", "close");
            this.Headers.Add("Cache-Control", "no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0");
            this.Headers.Add("Pragma", "no-cache");
            this.Headers.Add("Expires", "-1");
            this.Headers.Add("Access-Control-Allow-Origin", "*");
            this.ContentType = "multipart/x-mixed-replace;boundary=Ba4oTvQMY8ew04N8dcnM";
            var footer = Encoding.ASCII.GetBytes("'r'n");
            this.Contents = stream =>
            {
                using(var writer = new BinaryWriter(stream))
                {
                  writer.Write(data);
                  writer.Write(footer);
                }
            };
        }
    }
}

标题与我从一个内置MJPEG服务器的IPCamera获得的标题相匹配,尽管Fiddler显示了正确的标题:

HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: multipart/x-mixed-replace;boundary=Ba4oTvQMY8ew04N8dcnM
Expires: -1
Server: IP Webcam Server 1.5 Microsoft-HTTPAPI/2.0
Access-Control-Allow-Origin: *
Date: Tue, 24 Nov 2015 21:23:29 GMT
Connection: close

在启用MJPEG的浏览器(Firefox)中尝试时,无法流式传输或显示任何内容。我注意到的另一件事是Transfer-Encoding: chunked,它不应该出现。

有什么想法吗?

如何使用Nancy编写MJPEG服务器

我认为这里的问题很容易解决。写入流后,它指向流的末尾。在返回响应之前,您需要将指针倒带到流的开头:

   stream.Seek(0, SeekOrigin.Begin);