天天看點

一起談.NET技術,WCF使用NetTcp傳輸檔案

  服務中有一個上傳二進制流的方法UpLoad:

[ServiceContract]

public interface IAddService

{

  [OperationContract]

  void UpLoad(byte[] file);

}

  (為了減少時間,采用了一點寫死)

public class AddService:IAddService

  public void UpLoad(byte[] file)

  {

    System.IO.File.WriteAllBytes("d:/8.rmvb", file);//将上傳的檔案放到D盤下并命名

  }

  App.config是WCF的重頭戲,這裡的配置直接影響到服務的成敗和性能。先定義一個netTcpBinding供服務使用:

<bindings>

<netTcpBinding>

<binding name="netTcpBindConfig"

closeTimeout="00:01:00"

openTimeout="00:01:00"

receiveTimeout="00:10:00"

sendTimeout="00:01:00"

transactionFlow="false"

transferMode="Buffered"

transactionProtocol="OleTransactions"

hostNameComparisonMode="StrongWildcard"

listenBacklog="10"

maxBufferPoolSize="2147483647 "

maxBufferSize="2147483647 "

maxConnections="10"

maxReceivedMessageSize="2147483647 ">

<readerQuotas maxDepth="32"

maxStringContentLength="2147483647 "

maxArrayLength="2147483647 "

maxBytesPerRead="4096"

maxNameTableCharCount="16384" />

<reliableSession ordered="true"

inactivityTimeout="00:10:00"

enabled="false" />

<security mode="Transport">

<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />

</security>

</binding>

</netTcpBinding>

</bindings>

  這個配置需要注意maxConnections="10" 這個選項,如果你想改成最大連接配接為100就會在運作時報下面的錯誤。查了一下MSDN,原來如果是windows7,xp,2000,vista在TCP的同時線上數量是有限制的,超出10就會報錯。而如果想要更大的連接配接數,需要部署到windows server上。

一起談.NET技術,WCF使用NetTcp傳輸檔案

  如果想傳輸大檔案,下面幾個配置也是必不可少的:

  maxBufferPoolSize="2147483647 "

  maxBufferSize="2147483647 "  

   maxReceivedMessageSize="2147483647 "

  當然,還有配額的大小:

<readerQuotas maxDepth="32" maxStringContentLength="2147483647 " maxArrayLength="2147483647 " maxBytesPerRead="4096" maxNameTableCharCount="16384" />

  配置Behavior:

<behaviors>

<serviceBehaviors>

<behavior name="WCFLibrary.UpdateUserBehavior">

<serviceMetadata/>

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

</behaviors>

  最後是服務:

<service behaviorConfiguration="WCFLibrary.UpdateUserBehavior" name="WCFLibrary.AddService">

<host>

<baseAddresses>

<add baseAddress="net.tcp://localhost:4506/AddService"/>

</baseAddresses>

</host>

<endpoint address="" binding="netTcpBinding" contract="WCFLibrary.IAddService" bindingConfiguration="netTcpBindConfig"></endpoint>

<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" ></endpoint>

</service>

  服務配置好後,啟動,用戶端使用net.tcp://localhost:4506/AddService/mex引用這個服務以便生成本地代理

  代碼都是很簡單的了:

protected void Page_Load(object sender, EventArgs e)

  DateTime start = DateTime.Now;

  AddService.AddServiceClient proxy = new AddService.AddServiceClient();

  proxy.UpLoad(System.IO.File.ReadAllBytes("f:/8.rmvb"));

  Response.Write(start+" 開 始---"+DateTime.Now+" 結 束");

  用時8秒種:

一起談.NET技術,WCF使用NetTcp傳輸檔案

  檔案資訊:

一起談.NET技術,WCF使用NetTcp傳輸檔案
一起談.NET技術,WCF使用NetTcp傳輸檔案

  檔案按照151M,傳輸時間是8秒來計算,大概用時為:151(M)/8(S)=18.875M/S.很不錯的速度,不是嗎?

繼續閱讀