WCF大資料量傳輸的詳細步驟

來源:互聯網
上載者:User

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())

 

一切搞定,如有疑問歡迎留言

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.