HttpListener将数据写入响应输出流

时间:2013-08-02 08:04:36

标签: c# streaming httplistener

我有一个基于HttpListener的小型本地Web服务器。服务器将文件提供给本地客户端应用程序解压缩并将文件写入

response.OutputStream;

但有时文件(视频)很大,我不认为始终将所有文件字节复制到输出流(内存)是个好主意。我想将服务文件流连接到响应输出流,如下所示:

response.OutputStream = myFileStream;

但-ok- response.OutputStream是只读的,所以我只能写字节 - 是否有办法进行某种部分写入(流式传输)?

问候。

1 个答案:

答案 0 :(得分:2)

您需要创建一个线程并将数据流转换为响应。 使用这样的东西:

在主线程中:

while (Listening)
{
    // wait for next incoming request
    var result = listener.BeginGetContext(ListenerCallback, listener);
    result.AsyncWaitHandle.WaitOne();
}

你班上的某个地方:

public static void ListenerCallback(IAsyncResult result)
{
    var listenerClosure = (HttpListener)result.AsyncState;
    var contextClosure = listenerClosure.EndGetContext(result);

    // do not process request on the dispatcher thread, schedule it on ThreadPool
    // otherwise you will prevent other incoming requests from being dispatched
    ThreadPool.QueueUserWorkItem(
        ctx =>
        {
            var response = (HttpListenerResponse)ctx;

            using (var stream = ... )
            {
                stream.CopyTo(response.ResponseStream);
            }

            response.Close();
        }, contextClosure.Response);
}
相关问题