共用方式為


Net.TCP 埠共用範例

本文說明 PortSharing 範例。

TCP/IP 通訊協定會使用稱為埠的16位數位,區分對相同電腦上執行之多個網路應用程式的連線。 如果應用程式正在接聽埠,則該埠的所有 TCP 流量都會傳送至該應用程式。 其他應用程式無法同時接聽該埠。

許多通訊協定都有其使用的標準或預設埠號碼。 例如,HTTP 通訊協定通常會使用 TCP 連接埠 80。 Internet Information Services (IIS) 具有接聽程式,可共用多個 HTTP 應用程式之間的埠。 IIS 會直接接聽埠,並根據訊息數據流內的資訊,將訊息轉送至適當的應用程式。 這可讓多個 HTTP 應用程式使用相同的埠號碼,而不需要競爭來保留埠以接收訊息。

NetTcp 連接埠共用是 Windows Communication Foundation (WCF)功能,同樣可讓多個網路應用程式共用單一埠。 NetTcp 埠共享服務會使用 net.tcp 通訊協定接受連線,並根據其目的地位址轉送訊息。

NetTcp 連接埠共用服務預設不會啟用。 執行此範例之前,您必須手動啟用服務。 如需詳細資訊,請參閱 如何:啟用 Net.TCP 連接埠共享服務。 如果停用服務,當伺服器應用程式啟動時,就會擲回例外狀況。

Unhandled Exception: System.ServiceModel.CommunicationException: The TransportManager failed to listen on the supplied URI using the NetTcpPortSharing service: failed to start the service because it is disabled. An administrator can enable it by running 'sc.exe config NetTcpPortSharing start= demand'.. ---> System.InvalidOperationException: Cannot start service NetTcpPortSharing on computer '.'. ---> System.ComponentModel.Win32Exception: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

藉由設定PortSharingEnabled系結或NetTcpBinding綁定項的 TcpTransportBindingElement 屬性,在伺服器上啟用埠共用。 客戶端不需要知道埠共用是如何設定的,也能在伺服器上使用此功能。

啟用港口共用

下列程式代碼示範如何在伺服器上啟用埠共用。 它會使用隨機 URI 路徑,在固定埠上啟動服務的實例 ICalculator 。 即使兩個服務可以共用相同的埠,其整體端點位址仍必須是唯一的,因此 NetTcp 埠共用服務可以將訊息路由傳送至正確的應用程式。

// Configure a binding with TCP port sharing enabled
NetTcpBinding binding = new NetTcpBinding();
binding.PortSharingEnabled = true;

// Start a service on a fixed TCP port
ServiceHost host = new ServiceHost(typeof(CalculatorService));
ushort salt = (ushort)new Random().Next();
string address = $"net.tcp://localhost:9000/calculator/{salt}";
host.AddServiceEndpoint(typeof(ICalculator), binding, address);
host.Open();

啟用埠共用后,您可以多次執行服務,而不會因為埠號碼發生衝突。 如果您更改程式碼以停用埠共享,啟動兩個服務複本時,第二個會因錯誤AddressAlreadyInUseException而失敗。

Unhandled Exception: System.ServiceModel.AddressAlreadyInUseException: There is already a listener on IP endpoint 0.0.0.0:9000. Make sure that you are not trying to use this endpoint multiple times in your application and that there are no other applications listening on this endpoint. ---> System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted

執行範例程式

您可以使用測試客戶端來檢查訊息是否已正確路由傳送至共用埠的服務。

class client
{
   static void Main(string[] args)
   {
      Console.Write("Enter the service number to test: ");
      ushort salt = ushort.Parse(Console.ReadLine());
      string address = $"net.tcp://localhost:9000/calculator/{salt}";
      ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(new NetTcpBinding());
      ICalculator proxy = factory.CreateChannel(new EndpointAddress(address));

      // Call the Add service operation.
      double value1 = 100.00D;
      double value2 = 15.99D;
      double result = proxy.Add(value1, value2);
      Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

      // Call the Subtract service operation.
      value1 = 145.00D;
      value2 = 76.54D;
      result = proxy.Subtract(value1, value2);
      Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

      // Call the Multiply service operation.
      value1 = 9.00D;
      value2 = 81.25D;
      result = proxy.Multiply(value1, value2);
      Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

      // Call the Divide service operation.
      value1 = 22.00D;
      value2 = 7.00D;
      result = proxy.Divide(value1, value2);
      Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

      Console.WriteLine();
      Console.WriteLine("Press <ENTER> to terminate client.");
      Console.ReadLine();

      factory.Close();
   }
}

服務的每個實例都會列印出其唯一號碼和位址。 例如,當您執行 service.exe時,可能會看到下列文字。

Service #4381 listening on net.tcp://localhost:9000/calculator/4381.
Press <ENTER> to terminate service.

當您執行 client.exe時,請輸入您在這裡看到的服務號碼。

Enter the service number to test: 4381
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714

Press <ENTER> to terminate client.

此範例可以藉由變更用戶端所使用的產生的位址,在跨計算機組態中執行。 在Client.cs中,變更端點位址格式字串,以符合您服務的新位址。 將「localhost」替換為伺服器電腦的 IP 位址。 進行這項變更之後,您必須重新編譯範例。

要設定、建置和執行範例,請執行以下步驟:

  1. 請使用下列命令安裝 ASP.NET 4.0。

    %windir%\Microsoft.NET\Framework\v4.0.XXXXX\aspnet_regiis.exe /i /enable
    
  2. 請確定您已針對 Windows Communication Foundation 範例 執行One-Time 安裝程式。

  3. 如先前的簡介一節所述,啟用 NetTcp 埠共用服務。

  4. 若要建置解決方案的 C# 或 Visual Basic .NET 版本,請遵循建置 Windows Communication Foundation 範例 中的指示。

  5. 若要在單一或跨計算機組態中執行範例,請遵循執行 Windows Communication Foundation 範例 中的指示。 執行此範例的特定詳細數據先前包含在執行範例一節中。