推送式流处理示例

Windows Communication Foundation (WCF) 具有用于处理流数据的不同模型。WCF 实现“拉取”模型,其中应用程序代码(服务)返回 Stream 的实例并依赖较低层次基础结构从此流中提取数据,然后将数据写出到网络。ASP.NET 使用“推送”模型:基础结构使用 OutputStream 属性创建输出流并将它提供给应用程序代码(IHttpHandler)使用。应用程序代码负责将数据写入流。两种模型都是有效的方法,通常以某种方式将这两种方法桥接。

提示

此示例需要安装 .NET Framework 3.5 版才能生成和运行。若要打开项目和解决方案文件,需要使用 Visual Studio 2008。

本示例演示如何使用 Web 编程模型处理使用 ASP.NET 方案的流。

服务

该服务实现两个操作,这些操作演示常见的 ASP.NET 方案,如以下代码所示。

[OperationContract]
        [WebGet(UriTemplate = "images")]
        public Message GetDynamicImage()
        {
            string text = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["text"];

            Bitmap theBitmap = GenerateImage(text);

            Message response = StreamMessageHelper.CreateMessage(MessageVersion.None, "", "image/jpeg",
                delegate(Stream outputStream)
                {
                    theBitmap.Save(outputStream, ImageFormat.Jpeg);
                });

            return response;
        }

请注意,GetDynamicImage() 方法返回 Message 而不是 StreamBodyWriter (DelegateBodyWriter) 的自定义实现用于实现“推送”流语义。

DelegateBodyWriter 采用委托参数,该参数将输出流作为输入。

public delegate void StreamWriterDelegate(Stream output);

class DelegateBodyWriter : BodyWriter
    {
        StreamWriterDelegate writer;

        public DelegateBodyWriter(StreamWriterDelegate writer)
            : base(false)
        {
            this.writer = writer;
        }

        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement("Binary");

            XmlWriterStream stream = new XmlWriterStream(writer);
            this.writer(stream);
            stream.Close();

            writer.WriteEndElement();
        }
    }

然后,在执行 RawStreamResponseMessage.OnWriteBodyContents() 期间调用 StreamWriterDelegate 委托。

XmlWriterStream 类是一个适配器,它通过 Message 类使用的 XmlDictionaryWriter 提供 Stream API。

您可以在 Web 浏览器中查看该示例的输出。若要与示例交互,请在服务运行时定位到以下 URL。

https://localhost:8000/images?text=Hello, world!

https://localhost:8000/text?text=Hello, world!

设置、生成和运行示例

  1. 请确保已经执行了 Windows Communication Foundation 示例的一次性安装过程

  2. 若要生成 C# 或 Visual Basic .NET 版本的解决方案,请按照生成 Windows Communication Foundation 示例中的说明进行操作。

  3. 若要用单机配置或跨计算机配置来运行示例,请按照运行 Windows Communication Foundation 示例中的说明进行操作。

另请参见

任务

流处理源示例

Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.