现在的位置: 首页 > 综合 > 正文

WCF大数据量传输的详细步骤

2013年10月09日 ⁄ 综合 ⁄ 共 4407字 ⁄ 字号 评论关闭

1.  新建一个空白解决方案解决方案WcfSolution。

2.  添加一个类库项目DBLibrary

首先添加一个序列化和反序列对象类MySerialize

///<summary>
        ///序列化对象
        ///</summary>
    public static byte[] SerializeArray<T>(T DataValues)
        {
           byte[] b;
           // 创建一个内存流
           MemoryStream ms = new MemoryStream();
           try
           {
               // 序列化对象
               BinaryFormatter binaryFormatter =new BinaryFormatter();
               // 将对象序列化为内存流
               binaryFormatter.Serialize(ms, DataValues);
               // 设置内存流的起始位置
               ms.Position = 0;
               // 读入到byte数组
               b = new byte[ms.Length];
               ms.Read(b, 0, b.Length);
           }
           catch (Exception ex)
           {
               throw ex;
           }
            finally
           {
               ms.Close();
               ms.Dispose();
           }
           return b;
        }
 
        ///<summary>
        ///反序列化对象
        ///</summary>
        public static T DeserializeArray<T>(byte[] DataValues)
        {
           T MyDataValues;
           // 创建一个内存流
           MemoryStream ms = new MemoryStream();
           try
           {
               // 序列化对象
               BinaryFormatter binaryFormatter =new BinaryFormatter();
               // 将byte数组到内存流             
               ms.Write(DataValues, 0, DataValues.Length);
               // 将内存流的位置到最开始位置              
               ms.Position = 0;
               // 反序列化成对象,创建出与原对象完全相同的副本         
               MyDataValues = (T)binaryFormatter.Deserialize(ms);
           }
           catch (Exception ex)
           {
               throw ex;
           }
           finally
           {
               ms.Close();
               ms.Dispose();
           }
           return MyDataValues;
        }

其二  添加一个数据结构类DBData(可以根据具体要求来声明)

[Serializable]
    public class DBData
    {
        public double BeginTime;
        public IList<double> TimeSpan;
     
    }

其三 添加一个组织数据类DBHelp

public classDBHelp
    {
       ///<summary>
        ///序列化对象
        ///</summary>
    public static DBData GetData()
        {
           return new DBData();  // 具体数据自己添加
        }
 
     
    }

3.  在WcfSolution中添加一个类库Services,主要是用于定义契约。

添加一个IGetByte接口

///<summary>
    ///服务契约
    ///</summary>
    [ServiceContract(Name = " IGetByte ",Namespace ="http://www.weifangyh.com")]
    public interface IGetByte
    {
        [OperationContract]
      byte[]GetDBData();
    }

添加一个GetByte类,实现IGetByte接口

  

  public class GetByte: IGetByte
    {
        public byte[]GetDBData()
        {
           DBData db = newDBHelp.GetData();
           
           return MySerialize.SerializeArray(db);
        }
  }

4.  在WcfSolution中添加一个控制台应用程序Host,主要作用是作为启动wcf程序的宿主。

一.添加一个app.config用来配置服务器设置

<?xmlversion="1.0"?>
<configuration>
 <system.serviceModel>
   <bindings>
        <basicHttpBinding>
            <binding name="basehttpbinding" transferMode="Streamed" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text">
                <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                           maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
            </binding>
        </basicHttpBinding>
   </bindings>
   
   <services>
     <service name="Services.GetByte" behaviorConfiguration="serviceBehavior">
          <endpoint address="GetByte" binding="basicHttpBinding" contract="Services.IGetByte">
            
          </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8050"/>
          </baseAddresses>
        </host>
     </service>
   </services>
 
   <!--这个节使用来配置服务的行为-->
   <behaviors>
     <serviceBehaviors>
        <behavior name="serviceBehavior">
          <!--指定元数据使用http的get方式获取-->
          <serviceMetadata httpGetEnabled="true"/>
            <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        
        </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
<startup><supportedRuntimeversion="v4.0"sku=".NETFramework,Version=v4.0"/></startup></configuration>
 

二.在Main方法中写启动服务代码

static void Main(string[]args)
        {
   ServiceHost host = newServiceHost(typeof(GetProductssList));
           host.Open();
           Console.WriteLine("服务已启动!");
}

5.  在WcfSolution中添加一个asp.net网站当作客户端。

先把Host宿主运行起来,网站中右键添加服务引用,在地址中输入服务地址http://localhost:8050/GetByte前往然后确定

自动生成web.config配置文件,在这里需要修改些配置,以实现接受大数据量,配置文件如下:

<system.serviceModel>
     
     <behaviors>
          <endpointBehaviors >
              <behaviorname="ClientBehavior">
                  <dataContractSerializer maxItemsInObjectGraph="2147483647" />
              </behavior>
          </endpointBehaviors>
         
     </behaviors>
   <bindings>
     <basicHttpBinding>
        <binding name="BasicHttpBinding_GetByte" closeTimeout="00:01:00" 
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" 
          maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"
           useDefaultWebProxy="true">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
             maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
     </basicHttpBinding>
   </bindings>
   <client>
     <endpoint address="http://localhost:8050/ GetByte " 
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ GetByte" 
        contract="ServiceReference_ GetByte.GetByte " 
        name="BasicHttpBinding_ GetByte" />
   </client>
 </system.serviceModel>

然后新建page页面,在代码中实现与服务通信获取数据

  

GetByteClient getListClient =newGetByteClient ();
DBData  db= MySerialize. DeserializeArray< DBData> (getListClient.GetDBData())

 

一切搞定,如有疑问欢迎留言

抱歉!评论已关闭.