I'm presenting a small sample I wrote to demonstrate the port sharing feature. The second part is the server application. 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 following code demonstrates enabling port sharing on the server. It starts an instance of the ICalculator service on a fixed port with a random URI path. Even though two services can share the same port, their overall endpoint addresses still need to be unique so that the Net.Tcp Port Sharing Service can route messages to the correct application.

// Define a service contract
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);

[OperationContract]
double Subtract(double n1, double n2);

[OperationContract]
double Multiply(double n1, double n2);

[OperationContract]
double Divide(double n1, double n2);
}

// Service class that implements the service contract public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
return n1 + n2;
}

public double Subtract(double n1, double n2)
{
return n1 - n2;
}

public double Multiply(double n1, double n2)
{
return n1 * n2;
}

public double Divide(double n1, double n2)
{
return n1 / n2;
}
}

class service
{
static void Main(string[] args)
{
// 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 = String.Format("net.tcp://localhost:5555/calculator/{0}", salt);
host.AddServiceEndpoint(typeof(ICalculator), binding, address);
host.Open();

Console.WriteLine("Service #{0} listening on {1}.", salt, address);
Console.WriteLine("Press <ENTER> to terminate service.");
Console.ReadLine();

host.Close();
}
}

With port sharing enabled, you can run the service multiple times without having a conflict over the port number. If you were to change the code to disable port sharing, starting up two copies of the service would result in the second failing with an AddressAlreadyInUseException.

Unhandled Exception: System.ServiceModel.AddressAlreadyInUseException: There is already a listener on IP endpoint 0.0.0.0:5555. 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

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