/// <summary> /// Called when the class initializes by <see cref="BaseEngine.Initialize"/>. Override it to add post constructor logic. /// </summary> public void OnInitialize() { // get the local machine name string hostName = System.Net.Dns.GetHostName(); // setup the services hosts[POKER_SERVICE] = new ServiceHost(concreteHelper); hosts[POKER_BROADCAST] = new ServiceHost(pokerBroadcast); hosts[POKER_HOST] = new ServiceHost(pokerHost); hosts[POKER_CHAT] = new ServiceHost(pokerChat); #if DEBUG // in debug mode, we want to know of the hosts faults foreach (ServiceHost host in hosts) { host.Faulted += new EventHandler(host_Faulted); } #endif // setup the poker service NetTcpBinding netTcp = new NetTcpBinding(SecurityMode.None, true); netTcp.ReliableSession.Ordered = true; netTcp.ReceiveTimeout = TimeSpan.FromMinutes(10); netTcp.SendTimeout = TimeSpan.FromSeconds(15); hosts[POKER_SERVICE].AddServiceEndpoint(typeof(IPokerService), netTcp, string.Format("net.tcp://{0}:{1}/PokerService", hostName, port)); // setup the host service netTcp = new NetTcpBinding(SecurityMode.None); netTcp.SendTimeout = TimeSpan.FromSeconds(15); hosts[POKER_HOST].AddServiceEndpoint(typeof(IPokerHost), netTcp, string.Format("net.tcp://{0}:{1}/PokerHost", hostName, port)); ServiceDiscoveryBehavior discoveryBehavior = new ServiceDiscoveryBehavior(); hosts[POKER_HOST].Description.Behaviors.Add(discoveryBehavior); hosts[POKER_HOST].AddServiceEndpoint(new UdpDiscoveryEndpoint()); discoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); // setup the broadcast service netTcp = new NetTcpBinding(SecurityMode.None, true); netTcp.ReliableSession.Ordered = true; netTcp.ReceiveTimeout = TimeSpan.FromMinutes(10); netTcp.SendTimeout = TimeSpan.FromSeconds(15); hosts[POKER_BROADCAST].AddServiceEndpoint(typeof(IPokerServiceBroadcast), netTcp, string.Format("net.tcp://{0}:{1}/PokerServiceBroadcast", hostName, port)); // setup the chat service netTcp = new NetTcpBinding(SecurityMode.None); netTcp.SendTimeout = TimeSpan.FromSeconds(15); hosts[POKER_CHAT].AddServiceEndpoint(typeof(IPokerRoomChat), netTcp, string.Format("net.tcp://{0}:{1}/PokerRoomChat", hostName, port)); // open all hosts foreach (ServiceHost host in hosts) { host.Open(); } concreteHelper.OnInitialize(); }
private void btnListen_Click(object sender, EventArgs e) { if (_serviceHost == null) { _serviceHost = new ServiceHost(typeof(SampleService), _baseAddress); { // Add an endpoint to the service ServiceEndpoint discoverableEndpoint = _serviceHost.AddServiceEndpoint( typeof(ISampleService), new BasicHttpBinding(), "/DiscoverableEndpoint"); // Add Scopes to the endpoint EndpointDiscoveryBehavior discoverableEndpointBehavior = new EndpointDiscoveryBehavior(); foreach (ListViewItem item in lvTypes.CheckedItems) { XmlQualifiedName type = new XmlQualifiedName(item.SubItems[0].Text, item.SubItems[1].Text); discoverableEndpointBehavior.ContractTypeNames.Add(type); } foreach (ListViewItem item in lvScopes.CheckedItems) { discoverableEndpointBehavior.Scopes.Add(new Uri(item.SubItems[0].Text)); } discoverableEndpointBehavior.Enabled = true; discoverableEndpoint.Behaviors.Add(discoverableEndpointBehavior); } // without this fragment, Probe does not work { ServiceDiscoveryBehavior sdb = new ServiceDiscoveryBehavior(); _serviceHost.Description.Behaviors.Add(sdb); UdpDiscoveryEndpoint discoveryEndpoint = new UdpDiscoveryEndpoint(SelectedVersion); discoveryEndpoint.TransportSettings.TimeToLive = 5; _serviceHost.AddServiceEndpoint(discoveryEndpoint); //discoveryEndpoint.Address = new EndpointAddress(new Uri("urn:uuid" + _guid.ToString())); } _serviceHost.Open(); btnListen.Text = "Stop"; } else { _serviceHost.Close(); _serviceHost = null; btnListen.Text = "Listen"; } }
/// <summary> /// 向服务宿主中添加服务发现终结点 /// </summary> /// <param name="host">被添加终结点的服务宿主</param> public static void AddDiscoveryEndpointToServiceHost(ServiceHost host) { if (host == null) { throw new ArgumentNullException("host"); } ServiceDiscoveryBehavior behavior = new ServiceDiscoveryBehavior(); behavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(behavior); host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); }
static void UseCase1Core(Uri serviceUri, AnnouncementEndpoint aEndpoint, DiscoveryEndpoint dEndpoint) { var host = new ServiceHost(typeof(TestService)); var sdb = new ServiceDiscoveryBehavior(); sdb.AnnouncementEndpoints.Add(aEndpoint); host.Description.Behaviors.Add(sdb); host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), serviceUri); host.Open(); Console.WriteLine("Type [CR] to quit ..."); Console.ReadLine(); host.Close(); }
public static void Configure(ServiceConfiguration config) { var binding = new NetTcpBinding(SecurityMode.Transport, true); config.EnableProtocol(binding); config.AddServiceEndpoint(new UdpDiscoveryEndpoint()); ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); config.Description.Behaviors.Add(serviceDiscoveryBehavior); }
public void Use2() { // This time with ServiceDiscoveryBehavior. var b = new EndpointDiscoveryBehavior(); IEndpointBehavior eb = b; var host = new ServiceHost(typeof(TestService)); var se = host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), new Uri("http://localhost:37564")); var sdb = new ServiceDiscoveryBehavior(); sdb.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); IServiceBehavior sb = sdb; se.Behaviors.Add(b); var bc = new BindingParameterCollection(); sb.AddBindingParameters(host.Description, host, host.Description.Endpoints, bc); eb.AddBindingParameters(se, bc); Assert.AreEqual(0, bc.Count, "#1"); Assert.AreEqual(0, host.Extensions.Count, "#1-2"); sb.Validate(host.Description, host); eb.Validate(se); // ... should "validate" not "apply dispatch behavior" do "add host extension" job? I doubt that. Assert.AreEqual(1, host.Extensions.Count, "#2-2"); var dse = host.Extensions.Find <DiscoveryServiceExtension> (); Assert.IsNotNull(dse, "#2-3"); Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#2-4"); Assert.AreEqual(2, se.Behaviors.Count, "#2-5"); // EndpointDiscoveryBehavior + discovery initializer. Assert.AreEqual(0, host.ChannelDispatchers.Count, "#3-1"); Assert.AreEqual(1, host.Description.Endpoints.Count, "#3-2"); Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#3-4"); // The IEndpointBehavior from EndpointDiscoveryBehavior, when ApplyDispatchBehavior() is invoked, publishes an endpoint. sb.ApplyDispatchBehavior(host.Description, host); Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#3-5"); // not yet published eb.ApplyDispatchBehavior(se, new EndpointDispatcher(new EndpointAddress("http://localhost:37564"), "ITestService", "http://tempuri.org/")); Assert.AreEqual(2, host.ChannelDispatchers.Count, "#3-6-1"); // for online and offline announcements Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#3-6-2"); // still not published. host.Open(); try { Assert.AreEqual(3, host.ChannelDispatchers.Count, "#4-1"); // for online and offline announcements Assert.AreEqual(1, dse.PublishedEndpoints.Count, "#4-2"); // The endpoint is published again. (Not sure if it's worthy of testing.) } finally { host.Close(); } }
public void UseHttpBinding() { var ahost = new ServiceHost(typeof(AnnouncementService)); var aendpoint = new AnnouncementEndpoint(new CustomBinding(new HttpTransportBindingElement()), new EndpointAddress("http://localhost:4989")); var ib = new InspectionBehavior(); object state = new object(); ib.RequestReceived += delegate { InspectionBehavior.State = state; return(null); }; aendpoint.Behaviors.Add(ib); ahost.AddServiceEndpoint(aendpoint); ahost.Open(); try { Assert.IsTrue(ib.DispatchBehaviorApplied, "#1"); var b = new ServiceDiscoveryBehavior(); b.AnnouncementEndpoints.Add(new AnnouncementEndpoint(new CustomBinding(new HttpTransportBindingElement()), new EndpointAddress("http://localhost:4989"))); IServiceBehavior sb = b; var host = new ServiceHost(typeof(TestService)); var se = host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), new Uri("http://localhost:37564")); var bc = new BindingParameterCollection(); sb.AddBindingParameters(host.Description, host, host.Description.Endpoints, bc); sb.Validate(host.Description, host); // ... should "validate" not "apply dispatch behavior" do "add host extension" job? I doubt that. var dse = host.Extensions.Find <DiscoveryServiceExtension> (); Assert.IsNotNull(dse, "#2"); sb.ApplyDispatchBehavior(host.Description, host); // The IEndpointBehavior from ServiceDiscoveryBehavior, when ApplyDispatchBehavior() is invoked, publishes an endpoint. se.Behaviors [0].ApplyDispatchBehavior(se, new EndpointDispatcher(new EndpointAddress("http://localhost:37564"), "ITestService", "http://tempuri.org/")); host.Open(); try { Assert.AreEqual(state, InspectionBehavior.State, "#3"); } finally { host.Close(); } } finally { ahost.Close(); } }
public static void Main() { Uri baseAddress = new Uri("http://localhost:8000/" + Guid.NewGuid().ToString()); // Create a ServiceHost for the CalculatorService type. ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress); serviceHost.AddServiceEndpoint(typeof(ICalculatorService), new WSHttpBinding(), String.Empty); ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); // Announce the availability of the service over UDP multicast serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); try { // Make the service discoverable over UDP multicast serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint()); serviceHost.Open(); Console.WriteLine("Calculator Service started at {0}", baseAddress); Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate the service."); Console.WriteLine(); Console.ReadLine(); serviceHost.Close(); } catch (CommunicationException e) { Console.WriteLine(e.Message); } catch (TimeoutException e) { Console.WriteLine(e.Message); } if (serviceHost.State != CommunicationState.Closed) { Console.WriteLine("Aborting the service..."); serviceHost.Abort(); } }
public static void Main() { Uri baseAddress = new Uri("net.tcp://localhost:9002/CalculatorService/" + Guid.NewGuid().ToString()); Uri announcementEndpointAddress = new Uri("net.tcp://localhost:9021/Announcement"); ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress); try { ServiceEndpoint netTcpEndpoint = serviceHost.AddServiceEndpoint(typeof(ICalculatorService), new NetTcpBinding(), string.Empty); // Create an announcement endpoint, which points to the Announcement Endpoint hosted by the proxy service. AnnouncementEndpoint announcementEndpoint = new AnnouncementEndpoint(new NetTcpBinding(), new EndpointAddress(announcementEndpointAddress)); ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(announcementEndpoint); // Make the service discoverable serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); serviceHost.Open(); Console.WriteLine("Calculator Service started at {0}", baseAddress); Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate the service."); Console.WriteLine(); Console.ReadLine(); serviceHost.Close(); } catch (CommunicationException e) { Console.WriteLine(e.Message); } catch (TimeoutException e) { Console.WriteLine(e.Message); } if (serviceHost.State != CommunicationState.Closed) { Console.WriteLine("Aborting the service..."); serviceHost.Abort(); } }
public void LaunchService() { ServiceAddress = new Uri(string.Format("net.tcp://" + Environment.MachineName + ":{0}/TestAgent", _portNumber)); _host = new ServiceHost(_service, ServiceAddress); var serviceDebugBehavior = _host.Description.Behaviors.Find <ServiceDebugBehavior>(); serviceDebugBehavior.IncludeExceptionDetailInFaults = true; try { var netTcpBinding = new NetTcpBinding(SecurityMode.None); var endpoint = _host.AddServiceEndpoint(typeof(ITestService), netTcpBinding, "TestAgent"); endpoint.Behaviors.Add(new ClientTrackerEndpointBehavior()); var throttle = new ServiceThrottlingBehavior { MaxConcurrentSessions = 100 }; _host.Description.Behaviors.Add(throttle); // Discovery var discoveryBehaviour = new ServiceDiscoveryBehavior(); _host.Description.Behaviors.Add(discoveryBehaviour); discoveryBehaviour.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); _host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); // Metadata publishing. Binding mexTcpBinding = MetadataExchangeBindings.CreateMexTcpBinding(); var behaviour = new ServiceMetadataBehavior(); _host.Description.Behaviors.Add(behaviour); _host.AddServiceEndpoint(typeof(IMetadataExchange), mexTcpBinding, string.Format("net.tcp://" + Environment.MachineName + ":{0}/TestAgent", _portNumber)); _host.Open(); } catch (CommunicationException ce) { _host.Abort(); } }
public void Use() { var b = new ServiceDiscoveryBehavior(); b.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); IServiceBehavior sb = b; var host = new ServiceHost(new Uri("http://localhost:37564")); var bc = new BindingParameterCollection(); sb.AddBindingParameters(host.Description, host, host.Description.Endpoints, bc); Assert.AreEqual(0, bc.Count, "#1"); Assert.AreEqual(0, host.Extensions.Count, "#2-1"); sb.Validate(host.Description, host); // ... should "validate" not "apply dispatch behavior" do "add host extension" job? I doubt that. Assert.AreEqual(1, host.Extensions.Count, "#2-2"); var dse = host.Extensions.Find <DiscoveryServiceExtension> (); Assert.IsNotNull(dse, "#2-3"); Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#2-4"); Assert.AreEqual(0, host.ChannelDispatchers.Count, "#3-1"); sb.ApplyDispatchBehavior(host.Description, host); Assert.AreEqual(0, host.Description.Endpoints.Count, "#3-2"); Assert.AreEqual(2, host.ChannelDispatchers.Count, "#3-3"); // for online and offline announcements Assert.AreEqual(0, dse.PublishedEndpoints.Count, "#3-4"); // discovery endpoints are not "published" int idx = 0; foreach (var cdisb in host.ChannelDispatchers) { var cdis = cdisb as ChannelDispatcher; string head = "#4." + idx + "."; Assert.IsNull(cdis, head + "dispatcher"); if (cdisb.Listener != null) { Assert.AreEqual("urn:schemas-microsoft-org:ws:2008:07:discovery", cdisb.Listener.Uri.ToString(), head + "uri"); } // else ... WHOA! .NET "OnlineAnnouncementChannelDispatcher" type does not seem to provide the listener. idx++; } }
static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(DiscoveryProxy), new Uri("http://10.168.197.122:8080/DiscoveryProxy"))) { ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); ServiceEndpoint sep = host.AddServiceEndpoint(typeof(IDiscoveryProxy), new BasicHttpBinding(), ""); sep.ListenUri = new Uri("http://10.168.197.122:8080/DiscoveryProxy/via"); ServiceDiscoveryBehavior sdb = new ServiceDiscoveryBehavior(); sdb.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(sdb); host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); host.Open(); Console.WriteLine("service is open"); Console.ReadLine(); host.Close(); } }
protected internal override object CreateBehavior() { ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); AnnouncementEndpoint announcementEndpoint; foreach (ChannelEndpointElement channelEndpointElement in this.AnnouncementEndpoints) { if (string.IsNullOrEmpty(channelEndpointElement.Kind)) { throw FxTrace.Exception.AsError( new ConfigurationErrorsException( SR2.DiscoveryConfigAnnouncementEndpointMissingKind( typeof(AnnouncementEndpoint).FullName))); } ServiceEndpoint serviceEndpoint = ConfigLoader.LookupEndpoint(channelEndpointElement, null); if (serviceEndpoint == null) { throw FxTrace.Exception.AsError( new ConfigurationErrorsException( SR2.DiscoveryConfigInvalidEndpointConfiguration( channelEndpointElement.Kind))); } announcementEndpoint = serviceEndpoint as AnnouncementEndpoint; if (announcementEndpoint == null) { throw FxTrace.Exception.AsError( new InvalidOperationException( SR2.DiscoveryConfigInvalidAnnouncementEndpoint( channelEndpointElement.Kind, serviceEndpoint.GetType().FullName, typeof(AnnouncementEndpoint).FullName))); } serviceDiscoveryBehavior.AnnouncementEndpoints.Add(announcementEndpoint); } return(serviceDiscoveryBehavior); }
/// <summary> /// Attaches a new endpoint to the given host. /// </summary> /// <param name="host">The host to which the endpoint should be attached.</param> /// <param name="implementedContract">The contract implemented by the endpoint.</param> /// <param name="localEndpoint">The ID of the local endpoint, to be used in the endpoint metadata.</param> /// <param name="allowAutomaticChannelDiscovery"> /// A flag that indicates whether or not the channel should provide automatic channel discovery. /// </param> /// <returns>The newly attached endpoint.</returns> public ServiceEndpoint AttachDiscoveryEntryEndpoint( ServiceHost host, Type implementedContract, EndpointId localEndpoint, bool allowAutomaticChannelDiscovery) { var endpoint = host.AddServiceEndpoint(implementedContract, GenerateBinding(), GenerateNewDiscoveryEntryAddress()); if (allowAutomaticChannelDiscovery) { var discoveryBehavior = new ServiceDiscoveryBehavior(); discoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(discoveryBehavior); host.Description.Endpoints.Add(new UdpDiscoveryEndpoint()); } var endpointDiscoveryBehavior = new EndpointDiscoveryBehavior(); endpointDiscoveryBehavior.Extensions.Add(new XElement("root", new XElement("EndpointId", localEndpoint.ToString()))); endpoint.Behaviors.Add(endpointDiscoveryBehavior); return endpoint; }
protected internal override object CreateBehavior() { ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); AnnouncementEndpoint announcementEndpoint; foreach (ChannelEndpointElement channelEndpointElement in this.AnnouncementEndpoints) { if (string.IsNullOrEmpty(channelEndpointElement.Kind)) { throw FxTrace.Exception.AsError( new ConfigurationErrorsException( SR2.DiscoveryConfigAnnouncementEndpointMissingKind( typeof(AnnouncementEndpoint).FullName))); } ServiceEndpoint serviceEndpoint = ConfigLoader.LookupEndpoint(channelEndpointElement, null); if (serviceEndpoint == null) { throw FxTrace.Exception.AsError( new ConfigurationErrorsException( SR2.DiscoveryConfigInvalidEndpointConfiguration( channelEndpointElement.Kind))); } announcementEndpoint = serviceEndpoint as AnnouncementEndpoint; if (announcementEndpoint == null) { throw FxTrace.Exception.AsError( new InvalidOperationException( SR2.DiscoveryConfigInvalidAnnouncementEndpoint( channelEndpointElement.Kind, serviceEndpoint.GetType().FullName, typeof(AnnouncementEndpoint).FullName))); } serviceDiscoveryBehavior.AnnouncementEndpoints.Add(announcementEndpoint); } return serviceDiscoveryBehavior; }
protected override void Opening(ServiceHost serviceHost) { var serviceDiscovery = serviceHost.Description.Behaviors.Find <ServiceDiscoveryBehavior>(); if (serviceDiscovery == null) { serviceDiscovery = new ServiceDiscoveryBehavior(); serviceHost.Description.Behaviors.Add(serviceDiscovery); } if (announceEndpoints != null) { serviceDiscovery.AnnouncementEndpoints.AddAll(announceEndpoints); } var serviceMetadata = serviceHost.Extensions.OfType <IWcfDiscoveryMetadata>().ToArray(); foreach (var endpoint in serviceHost.Description.NonSystemEndpoints()) { var discovery = endpoint.Behaviors.Find <EndpointDiscoveryBehavior>(); if (discovery == null) { discovery = new EndpointDiscoveryBehavior(); endpoint.Behaviors.Add(discovery); } discovery.Scopes.AddAll(scopes); discovery.Extensions.AddAll(metadata); var discoveryMetaadata = endpoint.Behaviors.OfType <IWcfDiscoveryMetadata>(); AddDiscoveryMetadata(discoveryMetaadata, discovery); AddDiscoveryMetadata(serviceMetadata, discovery); if (strict == false) { ExportMetadata(endpoint, discovery); } } AddDiscoveryEndpoint(serviceHost); }
public void StartSettingsService() { var baseAddress = new Uri(String.Format(@"net.tcp://localhost/WatchFolderService")); _serviceHost = new ServiceHost(typeof(SettingsService), baseAddress); _serviceHost.Opened += ServiceHostOpened; try { _serviceHost.AddServiceEndpoint(typeof(ISettingsService), new NetTcpBinding(), "SettingsService"); var discoveryBehavior = new ServiceDiscoveryBehavior(); discoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); _serviceHost.Description.Behaviors.Add(discoveryBehavior); _serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint()); _serviceHost.Open(); } catch (CommunicationException communicationException) { _logHelper.WriteEntry(String.Format("Error starting Settings Sevice : {0}", communicationException.Message), MessageType.Error); _serviceHost.Abort(); } }
protected override void OnStart(string[] args) { //Thread.Sleep(20000); Logger.Info("Service is starting. Operating system: {0}", Utils.GetOperatingSystemInfo()); AppDomain.CurrentDomain.UnhandledException += ApplicationDomainUnhandledException; _repository = new Repository(); _clientBroadcastService = new ClientBroadcastService(); _dentalApiFactoryService = new DentalApiFactoryService(_repository); _serverAppService = new ServerAppService(_repository, new ChewsiApi(), _dentalApiFactoryService, _clientBroadcastService); _serviceHost = new ServiceHost(_serverAppService); ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); _serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); _serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint()); var binding = new WSDualHttpBinding(WSDualHttpSecurityMode.Message) { OpenTimeout = new TimeSpan(0, 10, 0), CloseTimeout = new TimeSpan(0, 10, 0), SendTimeout = new TimeSpan(0, 10, 0), ReceiveTimeout = new TimeSpan(0, 10, 0), Security = new WSDualHttpSecurity { Mode = WSDualHttpSecurityMode.None } }; ServiceEndpoint endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IServerAppService)), binding, new EndpointAddress(Utils.GetAddressFromHost(System.Net.Dns.GetHostName()))); _serviceHost.AddServiceEndpoint(endpoint); _serviceHost.Open(); Logger.Info("The service is ready at {0}", string.Join(", ", _serviceHost.BaseAddresses)); }
protected virtual ServiceHost CreateAndConfigureDiscoverableServiceHost <T>(T serviceInstance, Uri baseAddress, bool isDuplex = false) { var serviceHost = new ServiceHost(serviceInstance, baseAddress); var serviceEndPoint = serviceHost.AddServiceEndpoint(typeof(T), ClientServerBindingHelper.GetBinding(isDuplex), string.Empty); serviceEndPoint.Behaviors.Add(new SciendoAuditBehavior()); // ** DISCOVERY ** // // make the service discoverable by adding the discovery behavior ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); // send announcements on UDP multicast transport serviceDiscoveryBehavior.AnnouncementEndpoints.Add( new UdpAnnouncementEndpoint()); // ** DISCOVERY ** // // add the discovery endpoint that specifies where to publish the services serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint()); return(serviceHost); }
/// <summary> /// Enables the discovery. /// </summary> /// <param name="host">The host.</param> public static void EnableDiscovery(this ServiceHostBase host) { var announcementEndpointUrl = ConfigurationHelper.CloudAnnounce; if (String.IsNullOrWhiteSpace(announcementEndpointUrl)) { var errorMessage = string.Format( "No value found for key '{0}' in configuration file" + ", please provide a key '{0}' in the section AppConfig and set its value to the appropriate announcement endpoint url", ConfigurationHelper.CloudAnnounce ); throw new ApplicationException(errorMessage); } var announcementEndpoint = new AnnouncementEndpoint( BindingFactory.CreateBindingFromKey(BindingFactory.Key.WsHttpBindingNoSecurity), new EndpointAddress(announcementEndpointUrl)); var discovery = new ServiceDiscoveryBehavior(); discovery.AnnouncementEndpoints.Add(announcementEndpoint); host.Description.Behaviors.Add(discovery); }
static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(ToUpperService), new Uri("http://localhost:8081/DiscoverMe")); host.AddServiceEndpoint(typeof(IToUpper), new BasicHttpBinding(), "ToUpper"); host.AddServiceEndpoint(typeof(IToUpper), new WS2007HttpBinding(), "ToUpper2"); host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true }); ServiceDiscoveryBehavior discoveryBehavior = new ServiceDiscoveryBehavior(); host.Description.Behaviors.Add(discoveryBehavior); host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); discoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Open(); Console.WriteLine("Service running"); Console.ReadKey(); }
public static void EnableDiscovery(this ServiceHost host, bool enableMEX = true) { if (host.Description.Endpoints.Count == 0) { host.AddDefaultEndpoints(); } host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); ServiceDiscoveryBehavior discovery = new ServiceDiscoveryBehavior(); discovery.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(discovery); if (enableMEX == true) { host.Description.Behaviors.Add(new ServiceMetadataBehavior()); foreach (Uri baseAddress in host.BaseAddresses) { Binding binding = null; if (baseAddress.Scheme == "net.tcp") { binding = MetadataExchangeBindings.CreateMexTcpBinding(); } if (baseAddress.Scheme == "net.pipe") { binding = MetadataExchangeBindings.CreateMexNamedPipeBinding(); } Debug.Assert(binding != null); if (binding != null) { host.AddServiceEndpoint(typeof(IMetadataExchange), binding, "MEX"); } } } }
public void Open() { logger.Debug("ScreenCastService::Open(...)"); try { var session = mediaStreamer.Session; var videoSettings = session.VideoSettings; var videoDeviceName = videoSettings.CaptureDevice?.Name ?? ""; var hostName = session.StreamName; if (!string.IsNullOrEmpty(videoDeviceName)) { hostName += " (" + videoDeviceName + ")"; } var audioSettings = session.AudioSettings; var audioDeviceName = audioSettings.CaptureDevice?.Name ?? ""; var communicationPort = session.CommunicationPort; if (communicationPort < 0) { communicationPort = 0; } if (communicationPort == 0) {// FIXME: переделать // если порт не задан - ищем свободный начиная с 808 //communicationPort = GetRandomTcpPort(); var freeTcpPorts = MediaToolkit.Utils.NetTools.GetFreePortRange(System.Net.Sockets.ProtocolType.Tcp, 1, 808); if (freeTcpPorts != null && freeTcpPorts.Count() > 0) { communicationPort = freeTcpPorts.FirstOrDefault(); } } session.CommunicationPort = communicationPort; var communicationIp = session.NetworkIpAddress; var address = session.CommunicationAddress; this.ListenUri = new Uri(address); this.HostName = hostName; this.ServerId = MediaToolkit.Utils.RngProvider.GetRandomNumber().ToString(); Dictionary <string, string> endpointExtensions = new Dictionary <string, string> {// инфа которая будет доступна как расширение в WSDiscovery { "HostName", HostName }, { "StreamId", ServerId }, { "StreamName", session.StreamName }, { "AudioInfo", audioDeviceName }, { "VideoInfo", videoDeviceName }, }; //NetHttpBinding binding = new NetHttpBinding //{ // ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), // SendTimeout = TimeSpan.FromSeconds(10), //}; //NetTcpSecurity security = new NetTcpSecurity //{ // Mode = SecurityMode.Transport, // Transport = new TcpTransportSecurity // { // ClientCredentialType = TcpClientCredentialType.Windows, // ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign, // }, //}; NetTcpSecurity security = new NetTcpSecurity { Mode = SecurityMode.None, }; var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.MaxValue,//TimeSpan.FromSeconds(10), SendTimeout = TimeSpan.FromSeconds(10), Security = security, // PortSharingEnabled = true, }; host = new ServiceHost(this, ListenUri); //host = new ServiceHost(this); //var endpoint = host.AddServiceEndpoint(typeof(IScreenCastService), binding, ""); var endpoint = host.AddServiceEndpoint(typeof(IScreenCastService), binding, ListenUri); if (communicationPort == 0) {// сейчас не работает на клиенте !! // нужно доделать клиент endpoint.ListenUriMode = System.ServiceModel.Description.ListenUriMode.Unique; } var endpointDiscoveryBehavior = new EndpointDiscoveryBehavior(); foreach (var key in endpointExtensions.Keys) { var element = new System.Xml.Linq.XElement(key, endpointExtensions[key]); endpointDiscoveryBehavior.Extensions.Add(element); } //var addrInfos = MediaToolkit.Utils.NetworkHelper.GetActiveUnicastIpAddressInfos(); //foreach (var addr in addrInfos) //{ // endpointDiscoveryBehavior.Scopes.Add(new Uri(uri, @"ListenAddr/" + addr.Address)); //} endpoint.EndpointBehaviors.Add(endpointDiscoveryBehavior); ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(serviceDiscoveryBehavior); //host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); host.Description.Endpoints.Add(new UdpDiscoveryEndpoint()); host.Opened += Host_Opened; host.Faulted += Host_Faulted; host.Closed += Host_Closed; host.Open(); foreach (var dispatcher in host.ChannelDispatchers) { var listener = dispatcher.Listener; if (listener != null) { var uri = listener.Uri; if (uri != null) { var _host = uri.Host; if (_host == session.NetworkIpAddress) { //получаем порт на котором работает служба // если порт задан динамически session.CommunicationPort = uri.Port; } logger.Info(uri); } } } logger.Debug("Service opened: " + ListenUri.ToString()); } catch (Exception ex) { logger.Error(ex); Close(); var caption = "Network Error"; var message = "Network host opening error. Check network port and other settings."; throw new StreamerException(message, caption); } }
internal static void InitializeHost(this ServiceHost host, ServerOptions options) { // Check to see if the service host already has a ServiceMetadataBehavior ServiceMetadataBehavior smb = host.Description.Behaviors.Find <ServiceMetadataBehavior>(); // If not, add one if (smb == null) { smb = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(smb); } if (options.EnableDiscovery) { // Check to see if the service host already has a ServiceDiscoveryBehavior ServiceDiscoveryBehavior sdiscb = host.Description.Behaviors.Find <ServiceDiscoveryBehavior>(); // If not, add one if (sdiscb == null) { sdiscb = new ServiceDiscoveryBehavior(); host.Description.Behaviors.Add(sdiscb); } } // Check to see if the service host already has a ServiceDebugBehavior ServiceDebugBehavior sdb = host.Description.Behaviors.Find <ServiceDebugBehavior>(); // If not, add one if (sdb == null) { sdb = new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }; host.Description.Behaviors.Add(sdb); } List <ServiceEndpoint> contractEndpoints = new List <ServiceEndpoint>(); // Setup the bindings if (options.Scheme.IsBindingScheme(BindingScheme.TCP)) { NetTcpBinding tcpBinding = (NetTcpBinding)BindingScheme.TCP.GetBinding(options); host.AddServiceEndpoint(typeof(IIPC), tcpBinding, ""); host.AddServiceEndpoint(typeof(IIPCDuplex), tcpBinding, ""); contractEndpoints.Add(host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), BindingScheme.TCP.GetEndpointAddress(options, true))); } if (options.Scheme.IsBindingScheme(BindingScheme.NAMED_PIPE)) { NetNamedPipeBinding namedPipeBinding = (NetNamedPipeBinding)BindingScheme.NAMED_PIPE.GetBinding(options); host.AddServiceEndpoint(typeof(IIPC), namedPipeBinding, ""); host.AddServiceEndpoint(typeof(IIPCDuplex), namedPipeBinding, ""); contractEndpoints.Add(host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), BindingScheme.NAMED_PIPE.GetEndpointAddress(options, true))); } if (options.EnableDiscovery) { host.AddServiceEndpoint(new UdpDiscoveryEndpoint(UdpDiscoveryEndpoint.DefaultIPv4MulticastAddress)); EndpointDiscoveryBehavior discoveryBehavior = new EndpointDiscoveryBehavior(); discoveryBehavior.Scopes.Add(new Uri($"id:{options.ProcessID}".ToLower())); foreach (KeyValuePair <string, string> scope in options.Scopes) { discoveryBehavior.Scopes.Add(new Uri($"{scope.Key}:{scope.Value}".ToLower())); } foreach (ServiceEndpoint endpoint in contractEndpoints) { endpoint.EndpointBehaviors.Add(discoveryBehavior); } } }
static void Main(string[] args) { IPHostEntry entry = Dns.GetHostEntry(""); string addr = "localhost"; for (int i = 0; i < entry.AddressList.Length; i++) { if (entry.AddressList[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { addr = entry.AddressList[i].ToString(); break; } } Uri baseAddress = new Uri("http://" + addr + ":8084/319D0A4D-2253-47DC-AC4A-C1951FF6667D"); ServiceHost serviceHost = new ServiceHost(typeof(ServiceHelloWCF), baseAddress); try { Binding binding; DiscoveryVersion ver; ver = DiscoveryVersion.WSDiscovery11; binding = new WSHttpBinding(SecurityMode.None); // To enable WSDiscoveryApril2005 and Soap12WSAddressingAugust2004 //ver = DiscoveryVersion.WSDiscoveryApril2005; //binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressingAugust2004, Encoding.UTF8), new HttpTransportBindingElement()); ServiceEndpoint wsEndpoint = serviceHost.AddServiceEndpoint(typeof(IServiceHelloWCF), binding, ""); EndpointDiscoveryBehavior endpointDiscoveryBehavior = new EndpointDiscoveryBehavior(); // Add the discovery behavior to the endpoint. wsEndpoint.Behaviors.Add(endpointDiscoveryBehavior); // Make the service discoverable over UDP multicast ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); // Announce the availability of the service over UDP multicast serviceDiscoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint(ver)); // Make the service discoverable over UDP multicast. serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint(ver)); // Announce the availability of the service over UDP multicast ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.HttpGetUrl = baseAddress; serviceHost.Description.Behaviors.Add(smb); serviceHost.Open(); Console.WriteLine("Hello World WCF Service started at {0}", baseAddress); Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate the service."); Console.WriteLine(); Console.ReadLine(); serviceHost.Close(); } catch (CommunicationException e) { Console.WriteLine(e.Message); } catch (TimeoutException e) { Console.WriteLine(e.Message); } if (serviceHost.State != CommunicationState.Closed) { Console.WriteLine("Aborting service..."); serviceHost.Abort(); } }
public static void EnableDiscovery(this ServiceHost host, Uri scope, bool enableMEX = true) { if (host.Description.Endpoints.Count == 0) { host.AddDefaultEndpoints(); } host.AddServiceEndpoint(new UdpDiscoveryEndpoint()); ServiceDiscoveryBehavior discovery = new ServiceDiscoveryBehavior(); discovery.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint()); host.Description.Behaviors.Add(discovery); if (enableMEX == true) { host.Description.Behaviors.Add(new ServiceMetadataBehavior()); foreach (Uri baseAddress in host.BaseAddresses) { Binding binding = null; if (baseAddress.Scheme == "net.tcp") { binding = MetadataExchangeBindings.CreateMexTcpBinding(); } if (baseAddress.Scheme == "net.pipe") { binding = MetadataExchangeBindings.CreateMexNamedPipeBinding(); } if (baseAddress.Scheme == "http") { binding = MetadataExchangeBindings.CreateMexHttpBinding(); } if (baseAddress.Scheme == "https") { binding = MetadataExchangeBindings.CreateMexHttpsBinding(); } Debug.Assert(binding != null); if (binding != null) { host.AddServiceEndpoint(typeof(IMetadataExchange), binding, "MEX"); } } } if (scope != null) { EndpointDiscoveryBehavior behavior = new EndpointDiscoveryBehavior(); behavior.Scopes.Add(scope); foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { if (endpoint.IsSystemEndpoint || endpoint is DiscoveryEndpoint || endpoint is AnnouncementEndpoint || endpoint is ServiceMetadataEndpoint) { continue; } endpoint.Behaviors.Add(behavior); } } }
private void StartService(string serverIP, string serverPort, string localPort) { if (!(NetworkingToolkit.ValidateIPAddress(serverIP) && NetworkingToolkit.ValidatePort(serverPort) && NetworkingToolkit.ValidatePort(localPort))) { throw new ArgumentException() { Source = "ListeningForm.StartService(string serverIP, string serverPort, string localPort)" } } ; ////endereço do player Uri baseAddress = new Uri(String.Format("net.tcp://{0}:{1}/PlayerService/{2}", NetworkingToolkit.LocalIPAddress, localPort, Guid.NewGuid())); ////endpoint para onde as mensagens de announcement serão enviadas Uri announcementEndpointAddress = new Uri(String.Format("net.tcp://{0}:{1}/Announcement", serverIP, serverPort)); //criar o host do serviço serviceHost = new ServiceHost(typeof(PlayerService), baseAddress); try { ////Adicionar um endpoint para o serviço //NetTcpBinding tcpBindingService = new NetTcpBinding(); //tcpBindingService.Security.Mode = SecurityMode.None; //Alterar a autenticação para um modelo melhor ////tcpBindingService.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.None; //tcpBindingService.MaxReceivedMessageSize = 10000000; //tcpBindingService.MaxBufferSize = 10000000; //tcpBindingService.MaxBufferPoolSize = 10000000; //ServiceEndpoint netTcpEndpoint = serviceHost.AddServiceEndpoint(typeof(IPlayer), tcpBindingService, string.Empty); //Criar um endpoint para o announcement server, que aponta para o DiscoveryProxy NetTcpBinding tcpBindingAnnouncement = new NetTcpBinding(); tcpBindingAnnouncement.Security.Mode = SecurityMode.None; //Alterar a autenticação para um modelo melhor ////http://nerdwords.blogspot.pt/2008/01/wcf-error-socket-connection-was-aborted.html AnnouncementEndpoint announcementEndpoint = new AnnouncementEndpoint(tcpBindingAnnouncement, new EndpointAddress(announcementEndpointAddress)); //Criar um DiscoveryBehaviour e adicionar o endpoint ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior(); serviceDiscoveryBehavior.AnnouncementEndpoints.Add(announcementEndpoint); #if EXPOSE_METADATA //Adicionar um endpoint MEX (Metadata EXchange) por TCP System.ServiceModel.Channels.BindingElement bindingElement = new System.ServiceModel.Channels.TcpTransportBindingElement(); System.ServiceModel.Channels.CustomBinding binding = new System.ServiceModel.Channels.CustomBinding(bindingElement); System.ServiceModel.Description.ServiceMetadataBehavior metadataBehavior = serviceHost.Description.Behaviors.Find <System.ServiceModel.Description.ServiceMetadataBehavior>(); if (metadataBehavior == null) { metadataBehavior = new System.ServiceModel.Description.ServiceMetadataBehavior(); serviceHost.Description.Behaviors.Add(metadataBehavior); } serviceHost.AddServiceEndpoint(typeof(System.ServiceModel.Description.IMetadataExchange), binding, "MEX"); #endif //Adicionar o serviceDiscoveryBehavior ao host para poder ser descoberto serviceHost.Description.Behaviors.Add(serviceDiscoveryBehavior); serviceHost.Open(); Clipboard.SetText(baseAddress.ToString()); } catch (CommunicationException e) { Log(e); } catch (TimeoutException e) { Log(e); } catch (Exception ex) { Log(ex); } } void serviceHost_UnknownMessageReceived(object sender, UnknownMessageReceivedEventArgs e) { Log("Mensagem desconhecida recebida"); Log(e.Message.ToString()); } void serviceHost_RefreshState(object sender, EventArgs e) { this.RefreshState(); }