public void Start() { _service = new WcfServerSide(); _host = new ServiceHost(_service, new Uri("net.tcp://localhost:8085")); ServiceThrottlingBehavior throttle; throttle = _host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior(); throttle.MaxConcurrentCalls = 100; throttle.MaxConcurrentSessions = 100; _host.Description.Behaviors.Add(throttle); } try { _host.Open(); } catch (Exception ex) { CWService.AppendConsoleLine(ex.Message); CWService.AppendConsoleLine(ex.StackTrace); } finally { } }
public void DefaultValues () { var t = new ServiceThrottlingBehavior (); Assert.AreEqual (10, t.MaxConcurrentSessions, "#1"); Assert.AreEqual (16, t.MaxConcurrentCalls, "#2"); Assert.AreEqual (26, t.MaxConcurrentInstances, "#3"); }
public ServiceHost CreateServiceHost(ClusterConfiguration clusterConfiguration) { var managerNode = new ManagerNode(clusterConfiguration); managerNode.Start(); var serviceHost = new ServiceHost(managerNode, new[] { new Uri(string.Format("http://localhost:{0}/brightstarcluster", Configuration.HttpPort)), new Uri(string.Format("net.tcp://localhost:{0}/brightstarcluster", Configuration.TcpPort)), new Uri(string.Format("net.pipe://localhost/{0}", Configuration.NamedPipeName)) }); var basicHttpBinding = new BasicHttpContextBinding { TransferMode = TransferMode.StreamedResponse, MaxReceivedMessageSize = int.MaxValue, SendTimeout = TimeSpan.FromMinutes(30), ReaderQuotas = XmlDictionaryReaderQuotas.Max, Namespace = "http://www.networkedplanet.com/schemas/brightstar" }; var netTcpContextBinding = new NetTcpContextBinding { TransferMode = TransferMode.StreamedResponse, MaxReceivedMessageSize = int.MaxValue, SendTimeout = TimeSpan.FromMinutes(30), ReaderQuotas = XmlDictionaryReaderQuotas.Max, Namespace = "http://www.networkedplanet.com/schemas/brightstar" }; var netNamedPipeBinding = new NetNamedPipeBinding { TransferMode = TransferMode.StreamedResponse, MaxReceivedMessageSize = int.MaxValue, SendTimeout = TimeSpan.FromMinutes(30), ReaderQuotas = XmlDictionaryReaderQuotas.Max, Namespace = "http://www.networkedplanet.com/schemas/brightstar" }; serviceHost.AddServiceEndpoint(typeof(IBrightstarClusterManagerService), basicHttpBinding, ""); serviceHost.AddServiceEndpoint(typeof(IBrightstarClusterManagerService), netTcpContextBinding, ""); serviceHost.AddServiceEndpoint(typeof(IBrightstarClusterManagerService), netNamedPipeBinding, ""); var throttlingBehavior = new ServiceThrottlingBehavior { MaxConcurrentCalls = int.MaxValue }; serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true }); serviceHost.Description.Behaviors.Add(throttlingBehavior); serviceHost.Closed += StopNode; return serviceHost; }
private void AddNetTcpBinding() { ServiceThrottlingBehavior throttling = new ServiceThrottlingBehavior(); //TODO (CR May 2010): we're limiting connections, but not applications int maximumSimultaneousConnections = ApplicationServiceSettings.Default.MaximumSimultaneousApplications; // because InstanceContextMode is PerSession // MaxConcurrentCalls = MaxConcurrentInstances = number of sessions throttling.MaxConcurrentSessions = throttling.MaxConcurrentInstances = maximumSimultaneousConnections; throttling.MaxConcurrentCalls = maximumSimultaneousConnections; Description.Behaviors.Add(throttling); NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None, false); //Give the individual apps a chance to timeout on their own before we fault the channel. if (ApplicationServiceSettings.Default.InactivityTimeoutMinutes > 0) netTcpBinding.ReceiveTimeout = TimeSpan.FromMinutes(ApplicationServiceSettings.Default.InactivityTimeoutMinutes + 1); netTcpBinding.MaxBufferPoolSize = ApplicationServiceSettings.Default.MaxBufferPoolSize; netTcpBinding.MaxReceivedMessageSize = ApplicationServiceSettings.Default.MaxReceivedMessageSize; LogSettings(netTcpBinding); // Add an endpoint for the given service contract ServiceEndpoint sep = AddServiceEndpoint(typeof(IApplicationService), netTcpBinding, "ApplicationServices"); sep.Behaviors.Add(new SilverlightFaultBehavior()); // override the default fault handling behaviour which does not work for Silverlight app. }
static void Main(string[] args) { //for (int i = 0; i < 10; i++) //{ // new Thread(delegate() // { // n++; // Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ";" + n); // }).Start(); //} ServiceHost host = new ServiceHost(typeof(TestService)); try { ServiceThrottlingBehavior stb = new ServiceThrottlingBehavior { MaxConcurrentCalls = 1, MaxConcurrentInstances = 1 }; host.AddServiceEndpoint(typeof(ITestService), new NetTcpBinding(), TestService.NetTcpAddress); host.Description.Behaviors.Add(stb); host.Open(); } catch { host.Abort(); } Console.WriteLine("Press to exit ..."); Console.ReadKey(); }
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { // This returns a tuple var exports = container.Catalog.GetExports(new ImportDefinition( e => MatchesContract(e, serviceType), null, ImportCardinality.ExactlyOne, true, false)).SingleOrDefault(); // exports.Item1.ToString() returns the name of the exporting type var implementationTypeName = exports.Item1.ToString(); // look into all loaded assemblies for the implementation type var implementationType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => t.FullName == implementationTypeName).SingleOrDefault(); var host = base.CreateServiceHost( implementationType, baseAddresses); host.Description.Behaviors.Add(new MefBehavior(this.container, implementationType, serviceType)); ServiceThrottlingBehavior throt = new ServiceThrottlingBehavior(); int maxConcurrentCalls; if (int.TryParse(System.Configuration.ConfigurationManager.AppSettings["WCF_MaxConcurrentCalls"], out maxConcurrentCalls)) throt.MaxConcurrentCalls = maxConcurrentCalls; host.Description.Behaviors.Add(throt); return host; }
private void AddNetTcpBinding() { var tcpBinding = new NetTcpBinding(SecurityMode.None, true) {MaxConnections = 100}; //To maxmize MaxConnections you have //to assign another port for mex endpoint //and configure ServiceThrottling as well var throttle = _host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior {MaxConcurrentCalls = 100, MaxConcurrentSessions = 100}; _host.Description.Behaviors.Add(throttle); } //Enable reliable session and keep //the connection alive for 20 hours. tcpBinding.ReceiveTimeout = new TimeSpan(20, 0, 0); tcpBinding.ReliableSession.Enabled = true; tcpBinding.ReliableSession.InactivityTimeout = new TimeSpan(20, 0, 10); _host.AddServiceEndpoint(typeof (IChat), tcpBinding, "tcp"); }
/// <summary> /// Can only call before opening the host /// </summary> public static void SetThrottle(this ServiceHost host, int maxCalls, int maxSessions, int maxInstances) { ServiceThrottlingBehavior throttle = new ServiceThrottlingBehavior(); throttle.MaxConcurrentCalls = maxCalls; throttle.MaxConcurrentSessions = maxSessions; throttle.MaxConcurrentInstances = maxInstances; host.SetThrottle(throttle); }
private void AddThrottlingBehavior() { var behavior = this.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (behavior == null) { behavior = new ServiceThrottlingBehavior(); this.Description.Behaviors.Add(behavior); } behavior.MaxConcurrentCalls = 50; behavior.MaxConcurrentInstances = 50; behavior.MaxConcurrentSessions = 50; }
public static void Main() { //var helloServiceModel = new DefaultServiceModel(WcfEndpoint.BoundTo(new NetTcpBinding()).At("net.tcp://localhost:9101/hello"));//.AddExtensions(new GlobalExceptionHandlerBehaviour(typeof(GlobalExceptionHandler))); var throttlingBehavior = new ServiceThrottlingBehavior { MaxConcurrentCalls = Environment.ProcessorCount * 16, MaxConcurrentSessions = (Environment.ProcessorCount * 16) + (Environment.ProcessorCount * 100), MaxConcurrentInstances = Environment.ProcessorCount * 100 }; var helloServiceModel = new DefaultServiceModel(WcfEndpoint.BoundTo(new NetTcpBinding()).At("net.tcp://localhost:9101/hello")).AddExtensions(new GlobalExceptionHandlerBehaviour(typeof(GlobalExceptionHandler)), throttlingBehavior ); helloServiceModel.OnCreated(host => { host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom; host.Authorization.ExternalAuthorizationPolicies = new System.Collections.ObjectModel.ReadOnlyCollection<System.IdentityModel.Policy.IAuthorizationPolicy>(new List<IAuthorizationPolicy>() { new CustomAuthorizationPolicy() }); //var od = host.Description.Endpoints[0].Contract.Operations.Find("Handle"); //var serializerBehavior = od.Behaviors.Find<DataContractSerializerOperationBehavior>(); //if (serializerBehavior == null) //{ // serializerBehavior = new DataContractSerializerOperationBehavior(od); // od.Behaviors.Add(serializerBehavior); //} //serializerBehavior.DataContractResolver = new SharedTypeResolver(); }); var windsorContainer = new WindsorContainer().AddFacility<WcfFacility>(); windsorContainer.Register( Component.For<LoggingCallContextInitializer>(), Component.For<LoggingBehavior>(), Component.For<IConsoleService>().ImplementedBy<ConsoleService>().AsWcfService(new DefaultServiceModel(WcfEndpoint.BoundTo(new NetTcpBinding()).At("net.tcp://localhost:9101/console"))), Component.For<IRequestHandlerService>().ImplementedBy<RequestHandlerService>().AsWcfService(new DefaultServiceModel(WcfEndpoint.BoundTo(new NetTcpBinding()).At("net.tcp://localhost:9101/requestHandler"))), Component.For<IHelloService>().ImplementedBy<HelloService>().AsWcfService(helloServiceModel) ); var hostFactory = new DefaultServiceHostFactory(windsorContainer.Kernel); var helloHost = hostFactory.CreateServiceHost<IHelloService>(); var consoleHost = hostFactory.CreateServiceHost<IConsoleService>(); var requestHandlerHost = hostFactory.CreateServiceHost<IRequestHandlerService>(); try { Console.ReadLine(); } finally { helloHost.Close(); consoleHost.Close(); requestHandlerHost.Close(); } }
private static ServiceHost GetServiceHost(string httpurl, string tcpUrl, string ip) { var baseTcpUri = new Uri(tcpUrl); var currentHost = new ServiceHost(typeof (MediaService), baseTcpUri); // var tcpBinding = new NetTcpBinding // { // Security = // { // Mode = SecurityMode.None, // Transport = {ClientCredentialType = TcpClientCredentialType.Windows}, // Message = {ClientCredentialType = MessageCredentialType.Windows} // }, // ReliableSession = {Enabled = true} // }; // currentHost.AddServiceEndpoint(typeof (IMediaContract), tcpBinding, baseTcpUri); var servicebeHavior = currentHost.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (servicebeHavior == null) { servicebeHavior = new ServiceThrottlingBehavior(); currentHost.Description.Behaviors.Add(servicebeHavior); } servicebeHavior.MaxConcurrentSessions = 1000; var behavior = currentHost.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (behavior == null) { behavior = new ServiceMetadataBehavior(); currentHost.Description.Behaviors.Add(behavior); } behavior.HttpGetUrl = new Uri(httpurl); behavior.HttpGetEnabled = true; var debugBehavior = currentHost.Description.Behaviors.Find<ServiceDebugBehavior>(); debugBehavior.IncludeExceptionDetailInFaults = true; debugBehavior.HttpHelpPageEnabled = true; debugBehavior.HttpHelpPageUrl = new Uri("http://" + ip + ":8880/Help"); currentHost.Opened += delegate { foreach (Uri url in currentHost.BaseAddresses) { Console.WriteLine("Listening address:{0}", url); } }; return currentHost; }
static void Main(string[] args) { var host = new ServiceHost(typeof(MyContractClient)); ServiceThrottlingBehavior throttle = host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior(); throttle.MaxConcurrentCalls = 12; throttle.MaxConcurrentSessions = 34; throttle.MaxConcurrentInstances = 56; host.Description.Behaviors.Add(throttle); } host.Open(); Thread.Sleep(1000); host.Close(); }
protected internal override object CreateBehavior() { ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior(); PropertyInformationCollection properties = base.ElementInformation.Properties; if (properties["maxConcurrentCalls"].ValueOrigin != PropertyValueOrigin.Default) { behavior.MaxConcurrentCalls = this.MaxConcurrentCalls; } if (properties["maxConcurrentSessions"].ValueOrigin != PropertyValueOrigin.Default) { behavior.MaxConcurrentSessions = this.MaxConcurrentSessions; } if (properties["maxConcurrentInstances"].ValueOrigin != PropertyValueOrigin.Default) { behavior.MaxConcurrentInstances = this.MaxConcurrentInstances; } return behavior; }
/// <summary> /// Can only call before opening the host /// </summary> public static void SetThrottle(this ServiceHost host, ServiceThrottlingBehavior serviceThrottle, bool overrideConfig) { if (host.State == CommunicationState.Opened) { throw new InvalidOperationException("Host is already opened"); } ServiceThrottlingBehavior throttle = host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { host.Description.Behaviors.Add(serviceThrottle); return; } if (overrideConfig == false) { return; } host.Description.Behaviors.Remove(throttle); host.Description.Behaviors.Add(serviceThrottle); }
static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(GeoManager), new Uri("net.tcp://localhost:11011"), new Uri("http://localhost:11010")); ServiceDebugBehavior behaviorFaults = host.Description.Behaviors.Find<ServiceDebugBehavior>(); if(behaviorFaults == null) { behaviorFaults = new ServiceDebugBehavior(); behaviorFaults.IncludeExceptionDetailInFaults = true; host.Description.Behaviors.Add(behaviorFaults); } ServiceThrottlingBehavior behaviorThrottling = host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if(behaviorThrottling==null) { behaviorThrottling = new ServiceThrottlingBehavior(); behaviorThrottling.MaxConcurrentSessions = 100; behaviorThrottling.MaxConcurrentCalls = 16; behaviorThrottling.MaxConcurrentInstances = 116; host.Description.Behaviors.Add(behaviorThrottling); } ServiceMetadataBehavior behaviorServiceMetadata = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if(behaviorServiceMetadata == null) { behaviorServiceMetadata = new ServiceMetadataBehavior(); behaviorServiceMetadata.HttpGetEnabled = true; host.Description.Behaviors.Add(behaviorServiceMetadata); } host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "MEXTcp"); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "MEXHttp"); host.Open(); Se Console.WriteLine("Press key to stop the service"); Console.ReadKey(); host.Close(); }
private ServiceThrottlingBehavior GetConfiguredServiceThrottlingBehaviour() { ServiceThrottlingBehavior behaviour = new ServiceThrottlingBehavior(); if (MaxConcurrentCalls > 0) { behaviour.MaxConcurrentCalls = MaxConcurrentCalls; } if (MaxConcurrentInstances > 0) { behaviour.MaxConcurrentInstances = MaxConcurrentInstances; } if (MaxConcurrentSessions > 0) { behaviour.MaxConcurrentSessions = MaxConcurrentSessions; } return behaviour; }
public void CreateSocket(object listen) { int port = 7634; Uri tcpAdrs = new Uri("net.tcp://0.0.0.0:" + port.ToString() + "/ClientTransferring"); Uri[] baseAdresses = { tcpAdrs }; Shost = new ServiceHost(typeof(TransferClass), baseAdresses); NetTcpBinding bin = new NetTcpBinding(SecurityMode.None, false); bin.MaxBufferPoolSize = (int)67108864; bin.MaxBufferSize = (int)67108864; bin.MaxReceivedMessageSize = (int)67108864; bin.SendTimeout = TimeSpan.FromSeconds(15); bin.ReaderQuotas.MaxArrayLength = 67108864; bin.ReaderQuotas.MaxBytesPerRead = 67108864; bin.ReaderQuotas.MaxStringContentLength = 67108864; bin.MaxConnections = 2000; ServiceThrottlingBehavior throttle; throttle = Shost.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior(); throttle.MaxConcurrentCalls = 1000; throttle.MaxConcurrentSessions = 1000; Shost.Description.Behaviors.Add(throttle); } Shost.AddServiceEndpoint(typeof(ITransfer), bin, "tcp"); ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior(); Shost.Description.Behaviors.Add(mBehave); Shost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://0.0.0.0:" + (port - 1).ToString() + "/ClientTransferring/mex"); try { Shost.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
/// <summary> /// ****** Internal use only. Use <see cref="GetMonitor"/> instead. /// </summary> /// <param name="host"></param> private ConnectionMonitor(ServiceHostBase host) { _host = host; ServiceThrottlingBehavior behaviour; if (_host.Description.Behaviors.Contains(typeof(ServiceThrottlingBehavior))) { behaviour = (ServiceThrottlingBehavior)_host.Description.Behaviors[typeof(ServiceThrottlingBehavior)]; } else { behaviour = new ServiceThrottlingBehavior(); } // Assume we are using PerCall for InstanceContext mode, // each time a client requests for study header, a new InstanceContext is created. // Max connections = min (MaxConcurrentCalls, MaxConcurrentInstances) // MaxConcurrentSessions has no effect _maxConnections = Math.Min(behaviour.MaxConcurrentCalls, behaviour.MaxConcurrentInstances); }
public PeerService(PeerNodeConfig config, ChannelCallback channelCallback, GetNeighborCallback getNeighborCallback, Dictionary<System.Type, object> services, IPeerNodeMessageHandling messageHandler) { this.config = config; this.newChannelCallback = channelCallback; this.getNeighborCallback = getNeighborCallback; this.messageHandler = messageHandler; if (services != null) { object obj2 = null; services.TryGetValue(typeof(IPeerConnectorContract), out obj2); this.connector = obj2 as IPeerConnectorContract; obj2 = null; services.TryGetValue(typeof(IPeerFlooderContract<Message, UtilityInfo>), out obj2); this.flooder = obj2 as IPeerFlooderContract<Message, UtilityInfo>; } this.serviceHost = new ServiceHost(this, new Uri[0]); ServiceThrottlingBehavior item = new ServiceThrottlingBehavior { MaxConcurrentCalls = this.config.MaxPendingIncomingCalls, MaxConcurrentSessions = this.config.MaxConcurrentSessions }; this.serviceHost.Description.Behaviors.Add(item); }
/// <summary> /// Starts server, sets properties and initialises service. /// </summary> /// <param name="ip">IP on which server will start</param> /// <param name="port">Port on which the service will run and listen.</param> /// <returns></returns> public string Start(string ip,string port) { //Define base addresses so all endPoints can go under it Uri tcpAdrs = new Uri("net.tcp://" + ip + ":" + port + "/WPFHost/"); //http protocol will run on address + 1111, reasoning: at home I have port forwarded 2 ports 7777 and 8888 :D Uri httpAdrs = new Uri("http://" + ip + ":" + (int.Parse(port) + 1111) + "/WPFHost/"); Uri[] baseAdresses = { tcpAdrs,httpAdrs}; _host = new ServiceHost(typeof(SharedComponents.ChatService), baseAdresses); /* NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None, true) { MaxBufferPoolSize = 67108864, MaxBufferSize = 67108864, MaxReceivedMessageSize = 67108864, TransferMode = TransferMode.Streamed, ReaderQuotas = { MaxArrayLength = 67108864, MaxBytesPerRead = 67108864, MaxStringContentLength = 67108864 }, MaxConnections = 100 };*/ //Updated: to enable text transefer of 64 MB NetTcpBinding tcpBinding=new NetTcpBinding("tcpBinding"); BasicHttpBinding httpBinding=new BasicHttpBinding("httpBinding"); //To maxmize MaxConnections you have to assign another port for mex endpoint //and configure ServiceThrottling as well var throttle = _host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior { MaxConcurrentCalls = 100, MaxConcurrentSessions = 100 }; _host.Description.Behaviors.Add(throttle); } //Enable reliable session and keep the connection alive for 20 hours. _host.AddServiceEndpoint(typeof(SharedComponents.IChat), tcpBinding, "tcp"); _host.AddServiceEndpoint(typeof(SharedComponents.IFileTransferService), httpBinding, "http"); //Define Metadata endPoint, So we can publish information about the service /*ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior(); _host.Description.Behaviors.Add(mBehave); _host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://" + ip + ":" + (int.Parse(port)-1111) + "/WPFHost/mex");*/ string output = ""; try { _host.Open(); } catch (Exception ex) { output= ex.Message; } finally { if (_host.State == CommunicationState.Opened) { } else { //mandatory "never get here" return value output += "bla"; } } return output; }
private void buttonStart_Click(object sender, RoutedEventArgs e) { buttonStart.IsEnabled = false; Uri tcpAdrs = new Uri("net.tcp://" + textBoxIP.Text.ToString() + ":" + textBoxPort.Text.ToString() + "/WPFHost/"); Uri httpAdrs = new Uri("http://" + textBoxIP.Text.ToString() + ":" + (int.Parse(textBoxPort.Text.ToString()) + 1).ToString() + "/WPFHost/"); Uri[] baseAdresses = { tcpAdrs, httpAdrs }; host = new ServiceHost(typeof(ChatServiceAssembly.ChatService), baseAdresses); NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None, true); //Updated: to enable file transefer of 64 MB tcpBinding.MaxBufferPoolSize = (int)67108864; tcpBinding.MaxBufferSize = 67108864; tcpBinding.MaxReceivedMessageSize = (int)67108864; tcpBinding.TransferMode = TransferMode.Buffered; tcpBinding.ReaderQuotas.MaxArrayLength = 67108864; tcpBinding.ReaderQuotas.MaxBytesPerRead = 67108864; tcpBinding.ReaderQuotas.MaxStringContentLength = 67108864; tcpBinding.MaxConnections = 100; //To maxmize MaxConnections you have to assign another port for mex endpoint //and configure ServiceThrottling as well ServiceThrottlingBehavior throttle; throttle = host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior(); throttle.MaxConcurrentCalls = 100; throttle.MaxConcurrentSessions = 100; host.Description.Behaviors.Add(throttle); } //Enable reliable session and keep the connection alive for 20 hours. tcpBinding.ReceiveTimeout = new TimeSpan(20, 0, 0); tcpBinding.ReliableSession.Enabled = true; tcpBinding.ReliableSession.InactivityTimeout = new TimeSpan(20, 0, 10); host.AddServiceEndpoint(typeof(ChatServiceAssembly.IChat), tcpBinding, "tcp"); //Define Metadata endPoint, So we can publish information about the service ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(mBehave); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://" + textBoxIP.Text.ToString() + ":" + (int.Parse(textBoxPort.Text.ToString()) - 1).ToString() + "/WPFHost/mex"); try { host.Open(); } catch (Exception ex) { labelStatus.Content = ex.Message.ToString(); } finally { if (host.State == CommunicationState.Opened) { labelStatus.Content = "Opened"; buttonStop.IsEnabled = true; } } }
public static Uri RegisterService(Type contract) { // See if contractType is decorated with the RemoteServiceClassAttribute var attr = contract.GetCustomAttributes(typeof(RemoteServiceClassAttribute), false); if (attr == null || attr.Length != 1) { // TODO throw new InvalidOperationException("Contracts must be decorated with the RemoteServiceClassAttribute for automatic service registration."); } var serviceType = ((RemoteServiceClassAttribute)attr[0]).Type.AssemblyQualifiedName; // Attempt to load type var service = Type.GetType(serviceType); if (!service.IsSubclassOf(typeof(RemoteServiceBase))) { // TODO throw new InvalidOperationException("Service class must derive from Jhu.Graywulf.RemoteService.RemoteServiceBase"); } if (service == null || contract == null) { throw new Exception("Type not found."); // TODO } // Everything is OK, initialize service lock (syncRoot) { var host = new ServiceHost( service, RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), "")); // Turn on detailed debug info var sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>(); if (sdb == null) { sdb = new ServiceDebugBehavior(); host.Description.Behaviors.Add(sdb); } sdb.IncludeExceptionDetailInFaults = true; // Turn on impersonation /* var sab = host.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); if (sab == null) { sab = new ServiceAuthorizationBehavior(); host.Description.Behaviors.Add(sab); } sab.ImpersonateCallerForAllOperations = true; */ // Unthrottle service to increase throughput // Service is behind a firewall, no DOS attacks will happen // TODO: copy these settings to the control endpoint var tb = host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (tb == null) { tb = new ServiceThrottlingBehavior(); host.Description.Behaviors.Add(tb); } tb.MaxConcurrentCalls = 1024; tb.MaxConcurrentInstances = Int32.MaxValue; tb.MaxConcurrentSessions = 1024; var endpoint = host.AddServiceEndpoint( contract, RemoteServiceHelper.CreateNetTcpBinding(), RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), service.FullName)); host.Open(); registeredServiceHosts.Add(contract.FullName, host); registeredEndpoints.Add(contract.FullName, endpoint); return endpoint.Address.Uri; } }
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase) { if (this.maxPoolSize < this.minPoolSize) { throw new InvalidOperationException(ResourceHelper.GetString("ExMinLargerThanMax")); } // throw if the instance context mode is Single ServiceBehaviorAttribute serviceBehavior = description.Behaviors.Find<ServiceBehaviorAttribute>(); if (serviceBehavior != null && serviceBehavior.InstanceContextMode == InstanceContextMode.Single) { throw new InvalidOperationException(ResourceHelper.GetString("ExInvalidContext")); } // We need ServiceThrottlingBehavior to run before us, because it properly // initializes the ServiceThrottle property of the endpoints. If there is // no ServiceThrottlingBehavior, we will create one and run it ourselves. // If there is one, we validate that it comes before us. int throttlingIndex = this.GetBehaviorIndex(description, typeof(ServiceThrottlingBehavior)); if (throttlingIndex == -1) { this.throttlingBehavior = new ServiceThrottlingBehavior(); this.throttlingBehavior.MaxConcurrentInstances = this.MaxPoolSize; // Forward the call if we created a ServiceThrottlingBehavior. ((IServiceBehavior)this.throttlingBehavior).Validate(description, serviceHostBase); } else { int poolingIndex = this.GetBehaviorIndex(description, typeof(ObjectPoolingAttribute)); if (poolingIndex < throttlingIndex) { throw new InvalidOperationException(ResourceHelper.GetString("ExThrottleBeforePool")); } } }
protected override void OnOpening() { base.OnOpening(); foreach (var ep in this.Description.Endpoints) { if (ep.Behaviors.Find<WebHttpBehavior>() != null) { ep.Behaviors.Remove<WebHttpBehavior>(); ep.Behaviors.Add(new WebHttpBehavior2() { EnableAspNetCustomErrors = this.EnableAspNetCustomErrors, EnableAutomaticHelpPage = this.EnableAutomaticHelpPage, HelpPageLink = this.HelpPageLink }); } CustomBinding binding = new CustomBinding(ep.Binding); if (this.MaxMessageSize != 0) { binding.Elements.Find<TransportBindingElement>().MaxReceivedMessageSize = this.MaxMessageSize; } if (this.TransferMode != TransferMode.Buffered) { binding.Elements.Find<HttpTransportBindingElement>().TransferMode = this.TransferMode; } if (this.ReaderQuotas != null) { this.ReaderQuotas.CopyTo(binding.Elements.Find<TextMessageEncodingBindingElement>().ReaderQuotas); } if (this.Interceptors.Count > 0) { binding.Elements.Insert(0, new RequestInterceptorBindingElement(this.Interceptors)); } ep.Binding = binding; } if (this.MaxConcurrentCalls != 0) { ServiceThrottlingBehavior throttlingBehavior = this.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttlingBehavior == null) { throttlingBehavior = new ServiceThrottlingBehavior(); this.Description.Behaviors.Add(throttlingBehavior); } throttlingBehavior.MaxConcurrentCalls = this.MaxConcurrentCalls; } ServiceAuthorizationBehavior authz = this.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); authz.PrincipalPermissionMode = this.PrincipalPermissionMode; if (authz.PrincipalPermissionMode == PrincipalPermissionMode.UseAspNetRoles && authz.RoleProvider == null && Roles.Enabled) { authz.RoleProvider = Roles.Provider; } }
/// <summary> /// host /// </summary> /// <param name="point"></param> /// <param name="debugbehavior"></param> /// <param name="throtbehavior"></param> /// <param name="bing"></param> private void OpenHost(ServicePoint point, ServiceDebugBehavior debugbehavior, ServiceThrottlingBehavior throtbehavior, NetTcpBinding bing, bool EnableBinaryFormatterBehavior,Uri baseAddress) { ServiceHost host = new ServiceHost(point.Name, new Uri("net.tcp://" + baseAddress)); #region behavior if (host.Description.Behaviors.Find<ServiceDebugBehavior>() != null) host.Description.Behaviors.Remove<ServiceDebugBehavior>(); if (host.Description.Behaviors.Find<ServiceThrottlingBehavior>() != null) host.Description.Behaviors.Remove<ServiceThrottlingBehavior>(); host.Description.Behaviors.Add(debugbehavior); host.Description.Behaviors.Add(throtbehavior); //大数据量传输时必须设定此参数 if (point.MaxItemsInObjectGraph != null) { if (host.Description.Behaviors.Find<DataContractSerializerOperationBehavior>() != null) host.Description.Behaviors.Remove<DataContractSerializerOperationBehavior>(); //通过反射指定MaxItemsInObjectGraph属性(传输大数据时使用) object obj = typeof(ServiceHost).Assembly.CreateInstance( "System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior" , true, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic , null, new object[] { false, (int)point.MaxItemsInObjectGraph }, null, null); IServiceBehavior datacontractbehavior = obj as IServiceBehavior; host.Description.Behaviors.Add(datacontractbehavior); } #endregion host.AddServiceEndpoint(point.Contract, bing, (point.Address.StartsWith("/") ? point.Address.TrimStart('/') : point.Address)); //自定义二进制序列化器 if (EnableBinaryFormatterBehavior) { System.ServiceModel.Description.ServiceEndpoint spoint = host.Description.Endpoints.Count == 1 ? host.Description.Endpoints[0] : null; if (spoint != null && spoint.Behaviors.Find<BinaryFormatterBehavior>() == null) { BinaryFormatterBehavior serializeBehavior = new BinaryFormatterBehavior(); spoint.Behaviors.Add(serializeBehavior); } } #region 增加拦截器处理 if (point.Address != "Com/FrameWork/Helper/Wcf/LoadBalance/IHeatBeat" && point.Address != "Com/FrameWork/Helper/Wcf/Monitor/IMonitorControl") { int endpointscount = host.Description.Endpoints.Count; WcfParameterInspector wcfpi = new WcfParameterInspector(); wcfpi.WcfAfterCallEvent += new Wcf.WcfAfterCall((operationName, outputs, returnValue, correlationState, AbsolutePath) => { if (WcfAfterCallEvent != null) { WcfAfterCallEvent(operationName, outputs, returnValue, correlationState, AbsolutePath); } }); wcfpi.WcfBeforeCallEvent += new Wcf.WcfBeforeCall((operationName, inputs, AbsolutePath, correlationState) => { if (WcfBeforeCallEvent != null) { WcfBeforeCallEvent(operationName, inputs, AbsolutePath, correlationState); } }); for (int i = 0; i < endpointscount; i++) { if (host.Description.Endpoints[i].Contract.Name != "IMetadataExchange") { int Operationscount = host.Description.Endpoints[i].Contract.Operations.Count; for (int j = 0; j < Operationscount; j++) { host.Description.Endpoints[i].Contract.Operations[j].Behaviors.Add(wcfpi); } } } } #endregion #region 注册事件 //错误状态处理 host.Faulted += new EventHandler((sender, e) => { if (WcfFaultedEvent != null) { WcfFaultedEvent(sender, e); } }); //关闭状态处理 host.Closed += new EventHandler((sender, e) => { if (WcfClosedEvent != null) { WcfClosedEvent(sender, e); } //如果意外关闭,再次打开监听 if (isStop) return; services.Remove(host); OpenHost(point, debugbehavior, throtbehavior, bing, EnableBinaryFormatterBehavior,baseAddress); }); #endregion host.Open(); services.Add(host); }
public static void StartService(int port) { try { ILogService logService = new FileLogService(typeof(DataEngine)); logService.Info("启动数据服务引擎..."); // UriBuilder builder = new UriBuilder(Uri.UriSchemeNetTcp, "localhost", port, "/Data"); UriBuilder builder = new UriBuilder(Uri.UriSchemeNetPipe, "localhost"); _host = new ServiceHost(typeof(DataService), builder.Uri); ServiceThrottlingBehavior throttling = _host.Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttling != null) { throttling.MaxConcurrentSessions = maxConnections; } else { throttling = new ServiceThrottlingBehavior(); throttling.MaxConcurrentSessions = maxConnections; _host.Description.Behaviors.Add(throttling); } //GlobalErrorBehaviorAttribute errorBehavior = _host.Description.Behaviors.Find<GlobalErrorBehaviorAttribute>(); //if (errorBehavior == null) //{ // _host.Description.Behaviors.Add(errorBehavior); //} _host.AddServiceEndpoint(typeof(IDataService), CommunicationSettingsFactory.CreateDataServicePipeBinding(Timeout), "IDataService"); _host.AddServiceEndpoint(typeof(IPingService), CommunicationSettingsFactory.CreateDataServicePipeBinding(Timeout), "IPingService"); _host.Open(); } catch (Exception ex) { _logService.Error(string.Format("ExistCatch:Error:<-{0}->:{1} \r\n Error detail:{2}", "StartService", ex.Message, ex.ToString())); } }
/// <summary> /// Validates the specified description. /// </summary> /// <param name="description">The description.</param> /// <param name="serviceHostBase">The service host base.</param> void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase) { if (maxPoolSize < minPoolSize) { throw new InvalidOperationException(ResourceHelper.GetString("ExMinLargerThanMax")); } ServiceBehaviorAttribute serviceBehavior = description.Behaviors.Find<ServiceBehaviorAttribute>(); if (serviceBehavior != null && serviceBehavior.InstanceContextMode == InstanceContextMode.Single) { throw new InvalidOperationException(ResourceHelper.GetString("ExInvalidContext")); } int throttlingIndex = GetBehaviorIndex(description, typeof(ServiceThrottlingBehavior)); if (throttlingIndex == -1) { throttlingBehavior = new ServiceThrottlingBehavior(); throttlingBehavior.MaxConcurrentInstances = MaxPoolSize; ((IServiceBehavior)throttlingBehavior).Validate(description, serviceHostBase); } else { int poolingIndex = GetBehaviorIndex(description, typeof(InstancePoolingAttribute)); if (poolingIndex < throttlingIndex) { throw new InvalidOperationException(ResourceHelper.GetString("ExThrottleBeforePool")); } } }
int Start(string strDataDir, out string strError) { strError = ""; CloseHosts(); string strInstanceName = ""; string strUrl = "net.pipe://localhost/dp2kernel/xe"; _host = new ServiceHost(typeof(KernelService)); HostInfo info = new HostInfo(); info.DataDir = strDataDir; _host.Extensions.Add(info); /// // 绑定协议 { Uri uri = null; try { uri = new Uri(strUrl); } catch (Exception ex) { strError = "dp2Kernel OnStart() 警告:发现不正确的协议URL '" + strUrl + "' (异常信息: " + ex.Message + ")。该URL已被放弃绑定。"; return -1; } if (uri.Scheme.ToLower() == "net.pipe") { _host.AddServiceEndpoint(typeof(IKernelService), CreateNamedpipeBinding0(), strUrl); } else { // 警告不能支持的协议 strError = "dp2Kernel OnStart() 警告:发现不能支持的协议类型 '" + strUrl + "'"; return -1; } } { string strMetadataUrl = "http://localhost:8001/dp2kernel/xe/"; if (strMetadataUrl[strMetadataUrl.Length - 1] != '/') strMetadataUrl += "/"; strMetadataUrl += "metadata"; ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri(strMetadataUrl); _host.Description.Behaviors.Add(behavior); this.MetadataUrl = strMetadataUrl; } if (_host.Description.Behaviors.Find<ServiceThrottlingBehavior>() == null) { ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior(); behavior.MaxConcurrentCalls = 50; behavior.MaxConcurrentInstances = 1000; behavior.MaxConcurrentSessions = 1000; _host.Description.Behaviors.Add(behavior); } // IncludeExceptionDetailInFaults ServiceDebugBehavior debug_behavior = _host.Description.Behaviors.Find<ServiceDebugBehavior>(); if (debug_behavior == null) { _host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true }); } else { if (debug_behavior.IncludeExceptionDetailInFaults == false) debug_behavior.IncludeExceptionDetailInFaults = true; } _host.Opening += new EventHandler(host_Opening); _host.Closing += new EventHandler(m_host_Closing); try { _host.Open(); } catch (Exception ex) { strError = "dp2Kernel OnStart() host.Open() 时发生错误: instancename=[" + strInstanceName + "]:" + ex.Message; return -1; } return 0; }
/// <summary> /// Can only call before opening the host. Does not override config values if present /// </summary> public static void SetThrottle(this ServiceHost host, ServiceThrottlingBehavior serviceThrottle) { host.SetThrottle(serviceThrottle, false); }
/// <summary> /// Changes the throttling behavior. /// </summary> private void ChangeThrottling() { ServiceThrottlingBehavior throttle = Description.Behaviors.Find<ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior(); Description.Behaviors.Add(throttle); } throttle.MaxConcurrentCalls = int.MaxValue; throttle.MaxConcurrentSessions = int.MaxValue; }