int availablePort = GetAvailablePort.GetPort(); Uri baseAddress = new Uri("http://localhost:" + availablePort + "/MyServer"); if (selfHost != null) { selfHost.Close(); selfHost = null; } // Create the ServiceHost. selfHost = new ServiceHost(typeof(MyService), baseAddress); try { // Configure the Binding. var binding = new BasicHttpBinding("BasicHttpBinding_IMyServiceContract"); // Add a ServiceDiscoveryBehavior. selfHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior()); // Add a UdpDiscoveryEndpoint. selfHost.AddServiceEndpoint(new UdpDiscoveryEndpoint()); // Add a service endpoint. selfHost.AddServiceEndpoint(typeof(IMyServiceContract), binding, baseAddress); // Start the service. selfHost.Open(); Console.WriteLine("MyServer Started" + "at: " + baseAddress); Console.WriteLine("Press <Enter> to terminate the service."); Console.WriteLine(); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); selfHost.Abort(); }
private static EndpointAddress FindMyServerServiceAddress() { // Create DiscoveryClient DiscoveryClient discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint()); // Create FindCriteria FindCriteria findCriteria = new FindCriteria(typeof(IMyServiceContract)); findCriteria.MaxResults = 1; // Find IMyServiceContract endpoints FindResponse findResponse = discoveryClient.Find(findCriteria); Console.WriteLine(); Console.WriteLine("Discovered {0} IMyServiceContract endpoint(s).", findResponse.Endpoints.Count); if (findResponse.Endpoints.Count > 0) { return findResponse.Endpoints[0].Address; } else { return null; } }