代码改变世界

WCF 第六章 序列化和编码 大数据流

2010-12-21 17:19  DanielWise  阅读(1415)  评论(1编辑  收藏  举报

WCF支持两种消息处理模式: 缓冲和流模式。缓冲是WCF中处理消息的默认模式。在这个模式下,整个消息在发送和接收之前被放入内存中。在大多数场景,缓冲消息是重要的而且有时需要支持一些诸如可信赖消息和数字签名的特性。然而,缓冲大消息将很容易导致系统资源耗尽并限制可扩展性。WCF支持另外一种使用流处理消息的模式。在这个模式中,在客户端和服务端的数据使用一个System.IO.Stream.Streaming。流模式一般在一个绑定或一个传输信道上使用。列表6.29 显示了如何在绑定配置中通过设置transferMode属性在netTcpBinding绑定打开流处理。transferMode属性的可以使用的值有Buffer,Streamed,SteamResponse和StreamRequest.这允许在客户端和服务端之间细粒度的流控制。

列表6.29 在netTcpBinding上允许流

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <client>
            <endpoint address="net.tcp://localhost/FileDownloadService" binding="netTcpBinding"
                bindingConfiguration="EnableStreamingOnNetTcp" contract="Contract.IFileDownload"
                name="FileDownload_netTcpEndpoint">
                <identity>
                    <userPrincipalName value="administrator@localhost.com" />
                </identity>
            </endpoint>
        </client>
        <bindings>
            <netTcpBinding>
                <binding name="EnableStreamingOnNetTcp" transferMode="Streamed"
                    maxReceivedMessageSize="2147483647">
                    <security mode="None">
                        <transport clientCredentialType="Windows">
                            <extendedProtectionPolicy policyEnforcement="Never" />
                        </transport>
                    </security>
                </binding>
            </netTcpBinding>
        </bindings>
        <services />
    </system.serviceModel>
</configuration>

  为了充分利用流的优势,操作契约需要使用一个System.IO.Stream的实例或者返回一个使用流的消息契约。列表6.30 显示了一个返回一个System.IO.Stream的文件下载服务契约的例子。

列表6.30 FileDownload 服务契约

using System.ServiceModel;
using System.IO;

namespace Contract
{
    [ServiceContract]
    public interface IFileDownload
    {
        [OperationContract]
        Stream GetFile(string fileName);
    }
}

  当大量数据使用时流不能在所有场景中工作。例如,如果在失败后需要可信赖消息,数字签名或者恢复,流方式是不能接受的。在这些场景,手动将数据切分成小块消息然后发送很多小块消息,最终由接收方对小块消息重组的方法是首选。这可以很容易的在WCF上层应用中使用。