Net.Tcp Port Sharing Sample, Part 1

For the next few days I'm going to present a small sample I wrote to demonstrate the port sharing feature. The first part presents background information about the feature. I'm looking for feedback to help make the sample better. Right now, the sample configures the endpoints in code rather than configuration because it uses randomly-generated addresses for the server. I may just tack on the configuration details at the end because other port sharing topics already cover that material.


The TCP/IP protocol uses a 16-bit number, called a port, to differentiate connections to multiple network applications running on the same machine. If an application is listening on a port, then all TCP traffic for that port goes to that application. Other applications cannot listen on that port at the same time.

Many protocols have a standard or default port number that they use. For example, the HTTP protocol typically uses TCP port 80. Internet Information Services (IIS) has a listener to share a port between multiple HTTP applications. IIS listens on the port directly and forwards messages to the appropriate application based on information inside the message stream. This allows multiple HTTP applications to use the same port number without having to compete to reserve the port for receiving messages.

Net.Tcp Port Sharing is a Windows Communication Foundation (WCF) feature that similarly allows multiple network applications to share a single port. The Net.Tcp Port Sharing Service accepts connections using the net.tcp protocol and forwards messages based on their destination address.

The Net.Tcp Port Sharing Service is not enabled by default. Before running this sample, you will need to manually enable the service. For more information, see How to: Install and Configure Port Sharing (this is another document in the SDK but it looks like it's still being written so I'm not making this a link). If the service is disabled, an exception will be thrown when the server application is started.

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

Port sharing is enabled on the server by setting the PortSharingEnabled property of the NetTcp binding or the TCP transport binding element. The client does not need to know how port sharing has been configured to use it on the server.

Next time: Net.Tcp Port Sharing Sample, Part 2