public bool Start() { ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, "Start"); bool result = false; try { if (_host == null) { lock (_lock) { if (_host == null) { // Host string hostName = Dns.GetHostName(); // Add the base address Type serviceType = typeof(ConfigStoreService); Uri pipeUri = new Uri(ConfigStoreManager.GetPipeName(Process.GetCurrentProcess().Id)); Log.Info(PROC, pipeUri.AbsoluteUri); // default servuce if (true) { _host = new WcfServiceHost(serviceType, null, new Uri[] { pipeUri }); Type[] interfaces = serviceType.GetInterfaces(); string serviceContractAttrString = typeof(ServiceContractAttribute).ToString(); if (interfaces != null) { foreach (Type iface in interfaces) { ServiceContractAttribute serviceContractAttr = (from c in iface.GetCustomAttributes(false) where c.ToString() == serviceContractAttrString select c).FirstOrDefault() as ServiceContractAttribute; if (serviceContractAttr != null) { // named pipe _host.AddServiceEndpoint(iface, CreateNamedPipeBinding(), pipeUri); } } } } // Mex endpoings _host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), "mex"); Log.Info(PROC, pipeUri.AbsoluteUri + "/mex"); } } } // default service host try { if (_host != null && _host.State == CommunicationState.Created) { _host.Open(); result = true; } } catch (Exception ex) { Log.Exception(PROC, ex); } } catch (Exception ex) { Log.Exception(PROC, ex); } return(result); }
protected void LoadServer() { try { tbLog.Clear(); tbServerList.Clear(); tbServerList.AppendText("服务列表:\r\n"); WriteTestLog(""); WriteTestLog("开始启动服务"); //加载所有服务的基础类型; Type svcType = null; ServiceHost defaultHost = null; Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location); ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel"); foreach (ServiceElement el in svcmod.Services.Services) { string sSpaceName = el.Name.Remove(el.Name.LastIndexOf('.')); WriteTestLog("启动服务......" + el.Name); WriteTestLog("启动服务......" + el.Name + " GetType"); svcType = Type.GetType(el.Name + "," + sSpaceName); WriteTestLog("启动服务......" + el.Name + " GetType OK"); WriteTestLog("启动服务......" + el.Name + " GetHost"); defaultHost = new ServiceHost(svcType); string fullpath = AppDomain.CurrentDomain.BaseDirectory + "hcSinri.pfx"; string password = "******"; X509Certificate2 certificate = new X509Certificate2(fullpath, password); defaultHost.Credentials.ServiceCertificate.Certificate = certificate; WriteTestLog("启动服务......" + el.Name + " GetHost OK"); WriteTestLog("启动服务......" + el.Name + " AddBehavior"); ServiceMetadataBehavior smb = defaultHost.Description.Behaviors.Find <ServiceMetadataBehavior>(); if (smb == null) { defaultHost.Description.Behaviors.Add(new ServiceMetadataBehavior()); } //暴露出元数据,以便能够让SvcUtil.exe自动生成配置文件 defaultHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); WriteTestLog("启动服务......" + el.Name + " AddBehavior OK"); WriteTestLog("启动服务......" + el.Name + " Open"); if (defaultHost.State != CommunicationState.Opening) { defaultHost.Open(); tbServerList.AppendText(el.Name); tbServerList.AppendText("\r\n"); } WriteTestLog("启动服务......" + el.Name + " Open OK"); hosts.Add(el.Name, defaultHost); } } catch (Exception e) { WriteTestLog("启动服务出错:" + e.Message); System.Diagnostics.EventLog evtlog = new System.Diagnostics.EventLog(); evtlog.Log = "Application"; evtlog.Source = ConfigurationManager.AppSettings["ServiceName"] ?? "hcPlatWindowsServer"; evtlog.WriteEntry(e.Message, EventLogEntryType.Error); } }
internal void AddTcpEndpoints() { host.AddServiceEndpoint(typeof(IRestaurantService), new NetTcpBinding(), TcpServiceAddress); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), TcpMexAddress); }
// Token: 0x06002167 RID: 8551 RVA: 0x0009AC34 File Offset: 0x00098E34 public bool Start(out Exception ex) { ex = null; if (this.isRunning) { ServerLocatorManager.Tracer.TraceDebug(0L, "Server Locator Manager is already started."); return(true); } bool flag = false; bool result; try { object obj; Monitor.Enter(obj = ServerLocatorManager.syncRoot, ref flag); if (this.isRunning) { ServerLocatorManager.Tracer.TraceDebug(0L, "Server Locator Manager is already started."); result = true; } else { Exception serviceHostException = null; try { if (this.m_restartManager == null) { ServerLocatorManager.Tracer.TraceDebug(0L, "Creating restart manager that will constantly monitor service."); this.m_restartManager = new ServerLocatorManager.RestartServerLocator(this, ServerLocatorManager.restartInterval); this.m_restartManager.Start(); } ServerLocatorManager.Tracer.TraceDebug(0L, "Creating caching active manager client for Server Locator Service."); this.ADConfigProvider = Dependencies.MonitoringADConfigProvider; this.CopyStatusLookup = Dependencies.MonitoringCopyStatusClientLookup; this.Counters = ServerLocatorManager.GetPerfCounters(); ServerLocatorManager.Tracer.TraceDebug <string>(0L, "Starting Server Locator Service on {0}.", ServerLocatorManager.baseAddress.AbsoluteUri); this.serviceHost = new ServiceHost(typeof(ServerLocator), new Uri[] { ServerLocatorManager.baseAddress }); this.serviceHost.Faulted += this.RestartServiceHost; NetTcpBinding netTcpBinding = new NetTcpBinding(); netTcpBinding.MaxBufferPoolSize = 16777216L; netTcpBinding.MaxBufferSize = 16777216; netTcpBinding.MaxConnections = 200; netTcpBinding.MaxReceivedMessageSize = 16777216L; netTcpBinding.ReaderQuotas.MaxDepth = 128; netTcpBinding.ReaderQuotas.MaxArrayLength = int.MaxValue; netTcpBinding.ReaderQuotas.MaxBytesPerRead = int.MaxValue; netTcpBinding.ReaderQuotas.MaxNameTableCharCount = int.MaxValue; netTcpBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue; this.serviceHost.AddServiceEndpoint(typeof(IServerLocator), netTcpBinding, "ServerLocator"); ServiceThrottlingBehavior serviceThrottlingBehavior = new ServiceThrottlingBehavior(); serviceThrottlingBehavior.MaxConcurrentCalls = RegistryParameters.WcfMaxConcurrentCalls; serviceThrottlingBehavior.MaxConcurrentSessions = RegistryParameters.WcfMaxConcurrentSessions; serviceThrottlingBehavior.MaxConcurrentInstances = RegistryParameters.WcfMaxConcurrentInstances; ServiceThrottlingBehavior serviceThrottlingBehavior2 = this.serviceHost.Description.Behaviors.Find <ServiceThrottlingBehavior>(); if (serviceThrottlingBehavior2 == null) { this.serviceHost.Description.Behaviors.Add(serviceThrottlingBehavior); } else { this.serviceHost.Description.Behaviors.Remove(serviceThrottlingBehavior2); this.serviceHost.Description.Behaviors.Add(serviceThrottlingBehavior); } ServiceMetadataBehavior item = new ServiceMetadataBehavior(); this.serviceHost.Description.Behaviors.Add(item); if (RegistryParameters.WcfEnableMexEndpoint) { ServerLocatorManager.Tracer.TraceDebug(0L, "Creating Mex binding."); ExAssert.RetailAssert(RegistryParameters.HighAvailabilityWebServiceMexPort != RegistryParameters.HighAvailabilityWebServicePort, "Metadata Exchange port should be different from Server Locator web service port."); Binding binding = MetadataExchangeBindings.CreateMexTcpBinding(); this.serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, ServerLocatorManager.baseMetadataExchangeAddress); } InvokeWithTimeout.Invoke(delegate() { InvalidOperationException serviceHostException; try { this.serviceHost.Open(); } catch (InvalidOperationException serviceHostException) { serviceHostException = serviceHostException; } catch (CommunicationException serviceHostException2) { serviceHostException = serviceHostException2; } catch (SocketException serviceHostException3) { serviceHostException = serviceHostException3; } catch (Win32Exception serviceHostException4) { serviceHostException = serviceHostException4; } if (serviceHostException != null) { ServerLocatorManager.Tracer.TraceError <string>(0L, "InokeWithTimeout() failed to start Server Locator Service communication channel. Error: {0}", serviceHostException.Message); } }, ServerLocatorManager.startTimeout); if (serviceHostException == null) { this.isRunning = true; ServerLocatorManager.Tracer.TraceDebug(0L, "Server Locator Service started."); ReplayEventLogConstants.Tuple_ServerLocatorServiceStarted.LogEvent(null, new object[] { ServerLocatorManager.baseAddress.AbsoluteUri }); return(true); } } catch (TimeoutException ex2) { ReplayEventLogConstants.Tuple_ServerLocatorServiceStartTimeout.LogEvent(null, new object[] { ServerLocatorManager.baseAddress.AbsoluteUri, this.GenerateDiagnosticException("Timeout during starting server locator WCF service from ServerLocatorManager.Start()", ex2).Message }); ex = ex2; } if (serviceHostException != null) { ex = serviceHostException; } if (ex != null) { ServerLocatorManager.Tracer.TraceError <string>(0L, "Start() failed to start Server Locator Service communication channel. Error: {0}", ex.Message); } if (this.serviceHost != null) { ServerLocatorManager.Tracer.TraceDebug(0L, "Aborting server locator service communication channel from Start()."); this.serviceHost.Abort(); } ServerLocatorManager.Tracer.TraceError <string, string>(0L, "Failed to start Server Locator Service on {0}. Error: {1}", ServerLocatorManager.baseAddress.AbsoluteUri, ex.Message); ReplayEventLogConstants.Tuple_ServerLocatorServiceFailedToStart.LogEvent(null, new object[] { ServerLocatorManager.baseAddress.AbsoluteUri, ex.Message }); this.m_restartManager.ChangeTimer(ServerLocatorManager.startNowInterval, ServerLocatorManager.restartInterval); result = false; } } finally { if (flag) { object obj; Monitor.Exit(obj); } } return(result); }
public void Start() { OnLog("SimpleServiceHost starting..."); _serviceHost?.Close(new TimeSpan(0, 0, 0, 5)); try { // Setup Service as Singleton service implementation _serviceInstance = new SimpleService.SimpleService(); _serviceInstance.Initialize(); var tcpAddress = $"net.tcp://localhost:8081/SimpleService"; #if DEBUG // On DEBUG builds, also listen to HTTP endpoint. This makes it easier to get WSDL for testing var httpAddress = $"http://localhost:8080/SimpleService"; var baseAdresses = new[] { new Uri(httpAddress), new Uri(tcpAddress) }; const bool httpGetEnabled = true; #else var baseAdresses = new[] { new Uri(tcpAddress) }; const bool httpGetEnabled = false; #endif _serviceHost = new ServiceHost(_serviceInstance, baseAdresses); // Enable metadata exchange for Service _serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = httpGetEnabled }); #if DEBUG // On DEBUG builds, include exception details in faults var sdb = _serviceHost.Description.Behaviors.Find <ServiceDebugBehavior>(); if (null != sdb) { sdb.IncludeExceptionDetailInFaults = true; } else { _serviceHost.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); } #endif // Add discoverable endpoints, using Dual HTTP and MEX bindings, for Service _serviceHost.AddServiceEndpoint(typeof(ISimpleService), GetTcpBinding, tcpAddress); _serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); _serviceHost.Open(); OnLog($"SimpleService listening on:\n - {string.Join("\n - ", _serviceHost.BaseAddresses)}"); } catch (Exception ex) { OnLog("Error: initializing SimpleService failed: " + ex.Message); if (ex.Message.Contains("HTTP could not register URL http")) { OnLog("Try useing the command: netsh http add urlacl http://+:8080/SimpleService/ user=Everyone"); } } }
static void Main(string[] args) { try { var address = "net.tcp://{0}:{1}/QLKHDataService"; string hostName = ConfigurationManager.AppSettings["HostNameOrIP"]; string portNumber = ConfigurationManager.AppSettings["PortNumber"]; // Define the base address for the service var baseAddress = new Uri(string.Format(address, hostName, portNumber)); // Create service host for the CalculatorService type and privide the base address using (var serviceHost = new ServiceHost(typeof(QLKHDataService), baseAddress)) { var smb = serviceHost.Description.Behaviors.Find <ServiceMetadataBehavior>(); if (smb == null) { smb = new ServiceMetadataBehavior { HttpGetEnabled = false, HttpsGetEnabled = false, MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 } }; ServiceThrottlingBehavior throttle = serviceHost.Description.Behaviors.Find <ServiceThrottlingBehavior>(); if (throttle == null) { throttle = new ServiceThrottlingBehavior { MaxConcurrentCalls = 1000, MaxConcurrentSessions = 1000, MaxConcurrentInstances = 1000 }; serviceHost.Description.Behaviors.Add(throttle); } serviceHost.Description.Behaviors.Add(smb); } serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); var binding = new NetTcpBinding { OpenTimeout = new TimeSpan(1, 30, 0), CloseTimeout = new TimeSpan(1, 30, 0), SendTimeout = new TimeSpan(1, 30, 0), ReceiveTimeout = new TimeSpan(1, 30, 0), MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue }; binding.Security.Mode = SecurityMode.None; serviceHost.AddServiceEndpoint(typeof(IQLKHDataService), binding, ""); serviceHost.Open(); // The service can now be accessed. Console.WriteLine("The QLKH Data Service is ready. PORT : {0}", portNumber); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } }
/// <summary> /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests. /// </summary> /// <returns>A collection of listeners.</returns> protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners() { Binding binding = new BindingConfig().GetBindingWSHttp(); // set the proper way to expose the URI on cluster manager string host = this.Context.NodeContext.IPAddressOrFQDN; var endpointConfig = this.Context.CodePackageActivationContext.GetEndpoint("ServiceHttpEndPoint"); int port = endpointConfig.Port; string scheme = endpointConfig.Protocol.ToString(); string nodeName = this.Context.NodeContext.NodeName; string servicename = this.Context.ServiceTypeName; string uri = string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}/{3}/{4}.svc", scheme, host, port, nodeName, servicename); WcfCommunicationListener <IPressContract> pressListener = new WcfCommunicationListener <IPressContract>(this.Context, this, binding, new EndpointAddress(uri)); // Check to see if the service host already has a ServiceMetadataBehavior, If not, add one if (pressListener.ServiceHost.Description.Behaviors.Find <ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri(uri + "/mex/"); pressListener.ServiceHost.Description.Behaviors.Add(behavior); pressListener.ServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), uri + "/mex/"); } ServiceInstanceListener listener = new ServiceInstanceListener(context => pressListener); return(new[] { listener }); }
private void buttonStart_Click(object sender, RoutedEventArgs e) { buttonStart.IsEnabled = false; //Define base addresses so all //endPoints can go under it Uri tcpAdrs = new Uri("net.tcp://" + textBoxIP.Text.ToString() + ":" + textBoxPort.Text.ToString() + "/WpfHosting/"); Uri httpAdrs = new Uri("http://" + textBoxIP.Text.ToString() + ":" + (int.Parse(textBoxPort.Text.ToString()) + 1).ToString() + "/WpfHosting/"); Uri[] baseAdresses = { tcpAdrs, httpAdrs }; host = new ServiceHost( typeof(ServiceAssembly.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(ServiceAssembly.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() + "/WpfHosting/mex"); try { host.Open(); } catch (Exception ex) { labelStatus.Content = ex.Message.ToString(); } finally { if (host.State == CommunicationState.Opened) { labelStatus.Content = "Opened"; buttonStop.IsEnabled = true; } } }
static void Main(string[] args) { Log.InitLogger("FileTransferServiceLog"); var hostName = Dns.GetHostName(); Console.WriteLine($"Host: {hostName}"); var hostUri = Dns.GetHostEntry(hostName).AddressList .Where(x => x.AddressFamily == AddressFamily.InterNetwork) .Select(hostIp => new Uri($"net.tcp://{hostIp}/ImageService")) .First(); Console.WriteLine($"Service endpoint: {hostUri}"); // Dmitry Belkin TODO: In config string connectionString = @"Data Source=mkr0009;Initial Catalog=Media; User ID=db_user;Password=Qwerty_123; Integrated Security=False"; string connectionMongoString = @"mongodb://mkr0007:27017/PhotoStore"; Log.Instance.LogAsInfo($"{nameof(FileTransferServiceConsoleHost)}.{nameof(Program)}.{nameof(Main)}: Creating {nameof(FileTransferService)}"); var service = new FileTransferService( new ImageDbFileSource( new UnitOfWorkPhotoStorageMongo(connectionMongoString), new UnitOfWorkPhotoStorageSQL(connectionString))); Log.Instance.LogAsInfo($"{nameof(FileTransferServiceConsoleHost)}.{nameof(Program)}.{nameof(Main)}: Creating {nameof(FileTransferService)} is ended"); Log.Instance.LogAsInfo($"{nameof(FileTransferServiceConsoleHost)}.{nameof(Program)}.{nameof(Main)}: Creating {nameof(FileTransferService)}"); var serviceHost = new ServiceHost(service, hostUri); Log.Instance.LogAsInfo($"{nameof(FileTransferServiceConsoleHost)}.{nameof(Program)}.{nameof(Main)}: Creating {nameof(FileTransferService)} is ended"); serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior()); serviceHost.Description.Behaviors.Find <ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true; serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); //serviceHost.CloseTimeout = TimeSpan.MaxValue; //serviceHost.OpenTimeout = TimeSpan.MaxValue; var httpb = new NetTcpBinding() { TransferMode = TransferMode.Streamed, MaxReceivedMessageSize = 2147483647,//4294967295,//2147483647, MaxBufferSize = 2147483647, SendTimeout = new TimeSpan(4, 01, 0), CloseTimeout = new TimeSpan(4, 01, 0), OpenTimeout = new TimeSpan(4, 01, 0), ReceiveTimeout = new TimeSpan(4, 01, 0), ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxDepth = 2147483647, MaxStringContentLength = 2147483647, MaxArrayLength = 2147483647, MaxNameTableCharCount = 2147483647, MaxBytesPerRead = 2147483647 } }; var tcpb2 = new NetTcpBinding() { ReceiveTimeout = TimeSpan.MaxValue }; serviceHost.AddServiceEndpoint(typeof(IFileTransferService), httpb, "ImageService"); serviceHost.AddServiceEndpoint(typeof(IFileTransferServiceV2), tcpb2, "ImageService2"); Console.WriteLine("Initialization complete"); Console.WriteLine("Open service"); using (serviceHost) { Log.Instance.LogAsInfo($"{nameof(FileTransferServiceConsoleHost)}.{nameof(Program)}.{nameof(Main)}: Open ServiceHost..."); serviceHost.Open(); string cmd; do { Console.Write('>'); cmd = Console.ReadLine(); if (cmd == "copy") { Clipboard.SetText(hostUri.ToString()); } else if (cmd == "client") { System.Diagnostics.Process.Start("C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\wcftestclient.exe"); } } while (cmd != "exit"); serviceHost.Close(); Console.WriteLine("Service closed"); Log.Instance.LogAsInfo($"{nameof(FileTransferServiceConsoleHost)}.{nameof(Program)}.{nameof(Main)}: ServiceHost is closed."); } // Log.Instance.ExceptionInfo(e).LogAsError($"{nameof(FileTransferServiceConsoleHost)}.{nameof(Program)}.{nameof(Main)}: Open ServiceHost"); // Console.WriteLine(e); }
/// <summary> /// Creates a mex https binding. /// </summary> /// <returns></returns> public static System.ServiceModel.Channels.Binding GetMexHttpsBinding() { System.ServiceModel.Channels.Binding mexBinding = MetadataExchangeBindings.CreateMexHttpsBinding(); SetTimeouts(mexBinding); return(mexBinding); }
protected internal override Binding GetDefault() { return(MetadataExchangeBindings.CreateMexHttpBinding()); }
public virtual bool Start() { ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, "Start"); bool result = false; try { if (_host == null) { lock (_lock) { if (_host == null) { // Host string hostName = Dns.GetHostName(); // Service implementation factory instances IWcfExecutorServiceFactory executorServiceFactory = this.OnCreateExecutorService(); IWcfExecutorServiceFactory executorServiceFactoryRest = this.OnCreateExecutorServiceRest(); if (executorServiceFactory == null) { return(false); } Type[] knownTypes = executorServiceFactory.KnownTypes; // Service implementation types _serverInstance = executorServiceFactory.CreateSingletonInstance(this.ExecutorService) as IWcfExecutorService; Type serviceType = executorServiceFactory.ServiceType; Type serviceTypeRest = null; Type[] knownTypesRest = null; if (executorServiceFactoryRest != null) { _serverInstanceRest = executorServiceFactoryRest.CreateSingletonInstance(this.ExecutorService) as IWcfExecutorServiceRest; serviceTypeRest = executorServiceFactoryRest.ServiceType; knownTypesRest = executorServiceFactoryRest.KnownTypes; } // Base address and bindings AddressHelper.SetBasePath(_basePath); Uri tcpUri = null, httpUri = null, httpUriWeb = null; bool hasTcp = false, hasHttp = false, hasWebHttp = false; IList <Uri> hostAddresses = new List <Uri>(); Binding bindingTcp = null, bindingHttp = null, bindingWebHttp = null; // uris if (_tcpPort > 0) { tcpUri = AddressHelper.CreateTcpAddress(hostName, _tcpPort); bindingTcp = ContractBindingsHelper.CreateTcpBinding(); hostAddresses.Add(tcpUri); hasTcp = true; } if (_httpPort > 0) { httpUri = AddressHelper.CreateHttpAddress(hostName, _httpPort); bindingHttp = this.OnCreateHttpBinding(); hostAddresses.Add(httpUri); hasHttp = true; } if (_webHttpPort > 0) { httpUriWeb = AddressHelper.CreateHttpAddress(hostName, _webHttpPort); bindingWebHttp = ContractBindingsHelper.CreateWebHttpBinding(); hasWebHttp = true; } // default service if ((hasTcp || hasHttp) && (serviceType != null)) { _host = this.OnCreateServiceHost(_serverInstance, knownTypes, hostAddresses.ToArray()); var ifaceInfos = this.OnGetServiceContractInterfaces(serviceType); foreach (var ifaceInfo in ifaceInfos) { // web service host RESTFulAttribute restFul = (from c in ifaceInfo.ContractType.GetCustomAttributes(true) where c.ToString() == typeof(RESTFulAttribute).ToString() select c).FirstOrDefault() as RESTFulAttribute; if (restFul == null) { // tcp if (hasTcp) { _host.AddServiceEndpoint(ifaceInfo.ContractType, bindingTcp, string.Empty); Log.Info("Service Endpoint (Tcp) added for " + ifaceInfo.ContractType.FullName); } // http if (hasHttp) { _host.AddServiceEndpoint(ifaceInfo.ContractType, bindingHttp, string.Empty); Log.Info("Service Endpoint (Http) added for " + ifaceInfo.ContractType.FullName); } } } if (hasHttp) { ServiceMetadataBehavior metadataBehavior = _host.Description.Behaviors.Find <ServiceMetadataBehavior>(); if (metadataBehavior != null) { metadataBehavior.HttpGetEnabled = true; metadataBehavior.HttpGetUrl = httpUri; } } } // rest service if (hasWebHttp && (serviceTypeRest != null)) { var ifaceInfos = this.OnGetServiceContractInterfaces(serviceTypeRest); foreach (var ifaceInfo in ifaceInfos) { // web service host RESTFulAttribute restFul = (from c in ifaceInfo.ContractType.GetCustomAttributes(true) where c.ToString() == typeof(RESTFulAttribute).ToString() select c).FirstOrDefault() as RESTFulAttribute; if (restFul == null) { restFul = (from a in ifaceInfo.ContractType.GetInterfaces() from c in a.GetCustomAttributes(true) where c.ToString() == typeof(RESTFulAttribute).ToString() select c).FirstOrDefault() as RESTFulAttribute; } if (restFul != null) { // web service host if (_hostWeb == null) { _hostWeb = this.OnCreateWebServiceHost(_serverInstanceRest, knownTypesRest, new Uri[] { }); } // http Uri webUri = new Uri(Path.Combine(httpUriWeb.AbsoluteUri, ifaceInfo.ContractAttribute.Name)); _hostWeb.AddServiceEndpoint(ifaceInfo.ContractType, bindingWebHttp, webUri); Log.Info("Service Endpoint (WebHttp) added for " + ifaceInfo.ContractType.FullName); } } } // Mex endpoings if (hasTcp) { _host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); Log.Info("Mex Service Endpoint (Tcp) added"); } if (hasHttp) { _host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); Log.Info("Mex Service Endpoint (Http) added"); } // mex endpoint is not required for web http, so please don't uncomment this line if (_hostWeb != null) { //_hostWeb.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), // "mex"); } } } } // default service host try { if (_host != null && _host.State == CommunicationState.Created) { _host.Open(); _mreShutdown.Reset(); if (_serverInstance is IListener) { ((IListener)_serverInstance).Start(); } result = true; } } catch (Exception ex) { Log.Exception(PROC, ex); } // web service host if (result && (_hostWeb != null)) { try { if (_hostWeb != null && _hostWeb.State == CommunicationState.Created) { _hostWeb.Open(); if (_serverInstanceRest is IListener) { ((IListener)_serverInstanceRest).Start(); } result = true; } } catch (Exception ex) { Log.Exception(PROC, ex); } } } catch (Exception ex) { Log.Exception(PROC, ex); } return(result); }
static void Main(string[] args) { MetadataSet metadata = null; using (ChannelFactory <IMetadataExchange> channelFactory = new ChannelFactory <IMetadataExchange>(MetadataExchangeBindings.CreateMexHttpBinding(), new EndpointAddress("http://127.0.0.1:9999/calculatorservice/mex"))) { IMetadataExchange proxy = channelFactory.CreateChannel(); using (proxy as IDisposable) { string action = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get"; Message request = Message.CreateMessage(MessageVersion.Default, action); metadata = proxy.Get(request).GetBody <MetadataSet>(); } } using (XmlWriter writer = new XmlTextWriter("metadata.xml", Encoding.UTF8)) { metadata.WriteTo(writer); } Process.Start("metadata.xml"); }
protected virtual void AddMexBehavior(ServiceHost service) { service.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); }
/// <summary> /// see IDataServerServiceHost interface /// </summary> public void Start(Dictionary <string, object> args) { //configure wcf string localIp = null; int port = 0; int design_time_port = 0; WriteToLog_Info("Service host starting...", null); if (args.ContainsKey("ip")) { localIp = args["ip"] as string; } if (localIp == null) { throw new Exception("WCF session manager can not start because 'ip' parameter is not specified"); } if (args.ContainsKey("port")) { Int32.TryParse(args["port"].ToString(), out port); } if (port == 0) { throw new Exception("WCF session manager can not start because 'port' parameter is not specified"); } if (args.ContainsKey("design_time_port")) { Int32.TryParse(args["design_time_port"].ToString(), out design_time_port); } TimeSpan timeOut = new TimeSpan(0, 1, 0); List <Uri> aURIs = new List <Uri>(); aURIs.Add(new Uri(string.Format("net.tcp://{0}:{1}/DataServer_Service", localIp, port))); if (design_time_port != 0) { aURIs.Add(new Uri(string.Format("http://{0}:{1}/DataServer_Service", localIp, design_time_port))); } NetTcpBinding binding = new NetTcpBinding(); binding.TransactionFlow = false; binding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; binding.ReceiveTimeout = timeOut; binding.SendTimeout = timeOut; binding.OpenTimeout = timeOut; binding.CloseTimeout = timeOut; binding.ReliableSession.InactivityTimeout = timeOut; binding.Security.Mode = SecurityMode.None; binding.MaxBufferSize = 1073741823; binding.MaxReceivedMessageSize = 1073741823; // start WCF service m_ServiceCore = new DataServerWCFService(this.Name); m_ServiceCore.Start(); m_ServiceHost = new ServiceHost(m_ServiceCore, aURIs.ToArray()); m_ServiceHost.AddServiceEndpoint(typeof(IWCFService), binding, aURIs[0]); m_ServiceHost.Description.Behaviors.Add(new ServiceMetadataBehavior()); if (design_time_port != 0) { m_ServiceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); } m_ServiceHost.Open(); WriteToLog_Info("Service host started.", null); }
static void Main(string[] args) { Uri httpbaseAddress = new Uri("http://localhost:6790/MyHttpEndPoint"); Uri tcpbaseAddress = new Uri("net.tcp://localhost:6789"); ServiceHost sh = new ServiceHost(typeof(MulService), new Uri[] { httpbaseAddress, tcpbaseAddress }); ServiceEndpoint se = sh.AddServiceEndpoint(typeof(IMulService), new NetTcpBinding(), tcpbaseAddress); ServiceEndpoint httpse = sh.AddServiceEndpoint(typeof(IMulService), new WSHttpBinding(), httpbaseAddress); //ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); //smb.HttpGetEnabled = false; //sh.Description.Behaviors.Add(smb); ServiceEndpoint httpSeMex = sh.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:6790/MyHttpEndPoint/mex"); ServiceEndpoint tcpSeMex = sh.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://localhost:6789/mex"); sh.Open(); Console.WriteLine("Started....."); foreach (var item in sh.Description.Endpoints) { Console.WriteLine("Address: " + item.Address.ToString()); Console.WriteLine("Binding: " + item.Binding.Name.ToString()); Console.WriteLine("Contract: " + item.Contract.Name.ToString()); } Console.ReadLine(); sh.Close(); }
private static void InitServiceHost() { Uri tcpAdrs = new Uri("net.tcp://" + IP + ":" + PORT + "/Host/"); Uri httpAdrs = new Uri("http://" + IP + ":" + (PORT + 1).ToString() + "/Host/"); Uri[] baseAdresses = { tcpAdrs, httpAdrs }; host = new ServiceHost(typeof(POGApp.POGService), baseAdresses); NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None, true) { MaxBufferPoolSize = 67108864, MaxBufferSize = 67108864, MaxReceivedMessageSize = 67108864, 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 = 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(POGApp.IPOGService), 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://" + IP + ":" + (PORT - 1).ToString() + "/Host/mex"); try { host.Open(); } catch (Exception ex) { Console.WriteLine("Error opening host: " + ex); } finally { if (host.State == CommunicationState.Opened) { Console.WriteLine("Opened"); //labelStatus.Content = "Opened"; //buttonStop.IsEnabled = true; } } }
static void Main(string[] args) { try { Uri storageBaseAddress = new Uri("http://localhost:8080/s3storageGateway"); Uri preBaseAddress = new Uri("http://localhost:8080/s3pre"); Logger.Initialize(); Logger.LogInfo("ServiceHost is starting..."); if (WinSecurity.IsVistaOrHigher() && !WinSecurity.IsAdmin()) { Console.WriteLine("This application requires administrator rights to work"); Console.WriteLine("Press any key to restart the application with administrative rights, or close the program to exit..."); Console.ReadKey(); Logger.LogInfo("Restarting process as admin"); WinSecurity.RestartElevated(); return; } System.ServiceModel.ServiceHost storageHost = new System.ServiceModel.ServiceHost(typeof(StorageService), storageBaseAddress); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; storageHost.Description.Behaviors.Add(smb); // Add application endpoint storageHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); storageHost.AddServiceEndpoint(typeof(IGatewayService), ProxyFactory.CreateBinding(), ""); System.ServiceModel.ServiceHost preHost = new System.ServiceModel.ServiceHost(typeof(PreService), preBaseAddress); smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; preHost.Description.Behaviors.Add(smb); // Add application endpoint preHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); preHost.AddServiceEndpoint(typeof(IPreService), ProxyFactory.CreateBinding(), ""); preHost.Open(); storageHost.Open(); Logger.LogInfo("ServiceHosts are ready..."); Console.WriteLine("The storage services is ready at {0}", storageBaseAddress); Console.WriteLine("The pre services is ready at {0}", preBaseAddress); Console.WriteLine("Press <Enter> to stop the services."); Console.ReadKey(); Console.WriteLine(); Logger.LogInfo("ServiceHosts are closing..."); preHost.Close(); storageHost.Close(); Console.WriteLine("Services have been closed"); } catch (Exception e) { Console.WriteLine("Error hosting services. See log for details."); Logger.LogError("Unhandled exception in service hoster", e); } Console.WriteLine("Press a key to exit"); Console.ReadKey(); }
private void btnIniciar_Click(object sender, RoutedEventArgs e) { btnIniciar.IsEnabled = false; //Definir la dirección base para todas las conexiones Uri DireccionTCP = new Uri("net.tcp://" + txtIP.Text + ":" + txtPuerto.Text + "/ServicioChat/"); Uri DireccionHTTP = new Uri("http://" + txtIP.Text + ":" + (int.Parse(txtPuerto.Text) + 1).ToString() + "/ServicioChat/"); Uri[] DireccionesBase = { DireccionTCP, DireccionHTTP }; //Instancia del servicio Servidor = new ServiceHost( typeof(ServicioChat), DireccionesBase); NetTcpBinding tcpEnlace = new NetTcpBinding(SecurityMode.None, true); //Habilitar la transferencia de archivos de 64 MB tcpEnlace.MaxBufferPoolSize = (int)67108864; tcpEnlace.MaxBufferSize = 67108864; tcpEnlace.MaxReceivedMessageSize = (int)67108864; tcpEnlace.TransferMode = TransferMode.Buffered; tcpEnlace.ReaderQuotas.MaxArrayLength = 67108864; tcpEnlace.ReaderQuotas.MaxBytesPerRead = 67108864; tcpEnlace.ReaderQuotas.MaxStringContentLength = 67108864; tcpEnlace.MaxConnections = 100; //Configurar el número máximo de conexiones al servicio //lo cual incide en el comportamiento del mismo ServiceThrottlingBehavior controlServicio; controlServicio = Servidor.Description.Behaviors.Find <ServiceThrottlingBehavior>(); if (controlServicio == null) { controlServicio = new ServiceThrottlingBehavior(); controlServicio.MaxConcurrentCalls = 100; controlServicio.MaxConcurrentSessions = 100; Servidor.Description.Behaviors.Add(controlServicio); } //Configurar confiabilidad y durabilidad de la sesión tcpEnlace.ReceiveTimeout = new TimeSpan(20, 0, 0); tcpEnlace.ReliableSession.Enabled = true; tcpEnlace.ReliableSession.InactivityTimeout = new TimeSpan(20, 0, 10); Servidor.AddServiceEndpoint(typeof(IChat), tcpEnlace, "tcp"); //Habilitar la publicación de metadatos del servicio ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior(); Servidor.Description.Behaviors.Add(mBehave); Servidor.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://" + txtIP.Text.ToString() + ":" + (int.Parse(txtPuerto.Text.ToString()) - 1).ToString() + "/ServicioChat/mex"); // net.tcp://localhost:7996//ServicioChat/mex try { //Iniciar el servicio Servidor.Open(); } catch (Exception ex) { //No se pudo iniciar el servicio lblEstado.Text = ex.Message.ToString(); btnIniciar.IsEnabled = true; } finally { //Mostrar estado del servicio si se pudo abrir if (Servidor.State == CommunicationState.Opened) { lblEstado.Text = "Abierto"; btnDetener.IsEnabled = true; } } }
protected override void OnStart(string[] args) { //读取本置xml文件 Config.Current.LoadXml(); //设置当前连接字符串 BPMS.Common.AppSettings.ConnectionStrings.ModelContainer = Config.Current.GetConnectionString(); BPMS.Common.AppSettings.ConfigSettings.StaticAdminAccount = Config.Current.SuperAccount; BPMS.Common.AppSettings.ConfigSettings.StaticAdminPassword = Config.Current.SuperPassword; if (Config.Current.Binding == EBinding.WsHttpBinding) { WSHttpBinding wsHttpBinding = new WSHttpBinding(); wsHttpBinding.SendTimeout = new TimeSpan(0, 30, 0); wsHttpBinding.MaxReceivedMessageSize = 1024 * 1024 * 1024; //1G wsHttpBinding.MaxBufferPoolSize = 1024 * 1024 * 1024; //1G wsHttpBinding.Security.Mode = SecurityMode.None; wsHttpBinding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas(); wsHttpBinding.ReaderQuotas.MaxDepth = 1024 * 1024 * 1024; //1G wsHttpBinding.ReaderQuotas.MaxStringContentLength = 1024 * 1024 * 1024; //1G wsHttpBinding.ReaderQuotas.MaxArrayLength = 1024 * 1024 * 1024; //1G wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 1024 * 1024 * 1024; //1G wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 1024 * 1024 * 1024; //1G /******************************************/ serverHost = new ServiceHost(typeof(Service)); serverHost.Description.Endpoints.Clear(); serverHost.AddServiceEndpoint(typeof(IService), wsHttpBinding, String.Format("http://{0}:{1}/Service/", Config.Current.IP, Config.Current.Port)); } else if (Config.Current.Binding == EBinding.NetTcpBinding) { NetTcpBinding netTcpBinding = new NetTcpBinding(); netTcpBinding.TransferMode = TransferMode.Buffered; netTcpBinding.SendTimeout = new TimeSpan(0, 30, 0); netTcpBinding.MaxReceivedMessageSize = 1024 * 1024 * 1024; //1G netTcpBinding.MaxBufferSize = 1024 * 1024 * 1024; //1G netTcpBinding.MaxBufferPoolSize = 1024 * 1024 * 1024; //1G netTcpBinding.Security.Mode = SecurityMode.None; netTcpBinding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas(); netTcpBinding.ReaderQuotas.MaxDepth = 1024 * 1024 * 1024; //1G netTcpBinding.ReaderQuotas.MaxStringContentLength = 1024 * 1024 * 1024; //1G netTcpBinding.ReaderQuotas.MaxArrayLength = 1024 * 1024 * 1024; //1G netTcpBinding.ReaderQuotas.MaxBytesPerRead = 1024 * 1024 * 1024; //1G netTcpBinding.ReaderQuotas.MaxNameTableCharCount = 1024 * 1024 * 1024; //1G /******************************************/ serverHost = new ServiceHost(typeof(Service)); serverHost.Description.Endpoints.Clear(); serverHost.AddServiceEndpoint(typeof(IService), netTcpBinding, String.Format("net.tcp://{0}:{1}/Service/", Config.Current.IP, Config.Current.Port)); } if (serverHost.Description.Behaviors.Find <ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = false; //禁用浏览器查看元数据 serverHost.Description.Behaviors.Add(behavior); //添加元数据 //serverHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:8732/WCFService/mex"); //serverHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://localhost:8733/WCFService/mex"); } else { serverHost.Description.Behaviors.Find <ServiceMetadataBehavior>().HttpGetEnabled = false; } //必需在HttpGetEnabled=fakse后添加元数据设置 if (Config.Current.Binding == EBinding.WsHttpBinding) { serverHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), String.Format("http://{0}:{1}/Service/mex", Config.Current.IP, Config.Current.Port)); } else if (Config.Current.Binding == EBinding.NetTcpBinding) { serverHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), String.Format("net.tcp://{0}:{1}/Service/mex", Config.Current.IP, Config.Current.Port)); } serverHost.Opened += delegate { //Console.WriteLine("WCFService已经启动,按任意键终止服务!"); }; serverHost.Open(); ///**************************开启更新下载服务***********************************************/ BasicHttpBinding binding = new BasicHttpBinding(); binding.TransferMode = TransferMode.Streamed; binding.SendTimeout = new TimeSpan(0, 30, 0); binding.MaxReceivedMessageSize = 1024 * 1024 * 1024; //1G binding.MaxBufferPoolSize = 1024 * 1024 * 1024; //1G binding.MaxBufferSize = 1024 * 1024 * 1024; //1G binding.Security.Mode = BasicHttpSecurityMode.None; updateHost = new ServiceHost(typeof(AppUpdateService)); updateHost.Description.Endpoints.Clear(); updateHost.AddServiceEndpoint(typeof(IAppUpdateService), binding, String.Format("http://{0}:{1}/AppUpdateService/", Config.Current.IP, Config.Current.UpdatePort)); if (updateHost.Description.Behaviors.Find <ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = false; updateHost.Description.Behaviors.Add(behavior); } else { updateHost.Description.Behaviors.Find <ServiceMetadataBehavior>().HttpGetEnabled = false; } updateHost.Opened += delegate { //Console.WriteLine("AppUpdateService已经启动,按任意键终止服务!"); }; updateHost.Open(); //Console.Read(); }
protected internal override Binding GetDefault() { return(MetadataExchangeBindings.GetBindingForScheme(Uri.UriSchemeHttp)); }
private static void Main(string[] args) { ///Step 1 - Creates an instance of the Uri class to hold the base ///address of the service. Services are identified by a URL which ///contains a base address and an optional URI.The base address is ///formatted as follows:[transport]://[machine-name or domain][:optional port #]/[optional URI segment] ///The base address for the calculator service uses the HTTP transport, ///localhost, port 8000, and the URI segment "GettingStarted" Uri baseAddress = new Uri("http://localhost:8000/GettingStarted/"); w(baseAddress.ToString()); ///Step 2 – Creates an instance of the ServiceHost class to host the service. ///The constructor takes two parameters, the type of the class that ///implements the service contract, and the base address of the service. ServiceHost svcHost = new ServiceHost(typeof(CalculatorService), baseAddress); try { ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find <ServiceMetadataBehavior>(); if (smb == null) { smb = new ServiceMetadataBehavior(); } smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; svcHost.Description.Behaviors.Add(smb); // Add MEX endpoint svcHost.AddServiceEndpoint( ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex" ); // Add application endpoint svcHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService"); /////Step 3 – Creates a ServiceEndpoint instance. /////A service endpoint is composed of an address, a binding, and a service contract. /////The ServiceEndpoint constructor therefore takes the service contract interface type, /////a binding, and an address. /////The service contract is ICalculator, which you defined and /////implement in the service type. /////The binding used in this sample is WSHttpBinding /////which is a built-in binding that is used for connecting to endpoints that conform /////to the WS-* specifications. For more information about WCF bindings, /////see WCF Bindings Overview. /////The address is appended to the base address to /////identify the endpoint. The address specified in this code is "CalculatorService" /////so the fully qualified address for the endpoint is "http://localhost:8000/GettingStarted/CalculatorService". //svcHost.AddServiceEndpoint(typeof(ICalculator), // new WSHttpBinding(), "CalculatorService"); /////Step 4 – Enable metadata exchange. /////Clients will use metadata exchange to generate proxies that will be used to call the service operations. /////To enable metadata exchange create a ServiceMetadataBehavior instance, /////set it’s HttpGetEnabled property to true, /////and add the behavior to the System.ServiceModel.ServiceHost.Behaviors* /////collection of the ServiceHost instance. //ServiceMetadataBehavior smb; //smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>(); //if (smb == null) //{ // smb = new ServiceMetadataBehavior // { // HttpGetEnabled = true, // HttpsGetEnabled = true // }; //} //svcHost.Description.Behaviors.Add(smb); //Binding binding = MetadataExchangeBindings.CreateMexHttpBinding(); //svcHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, "MEX"); ///Step 5 – Open the ServiceHost to listen for incoming messages. ///Notice the code waits for the user to hit enter. ///If you do not do this, the app will close immediately and the service will shut down. ///Also notice a try/catch block used. ///After the ServiceHost has been instantiated, all other code is placed in a try/catch block. ///For more information about safely catching exceptions thrown by ServiceHost, ///see Use Close and Abort to release WCF client resources svcHost.Open(); Console.WriteLine("The service is ready: " + Assembly.GetEntryAssembly().GetName().Version.ToString()); Console.WriteLine("Press <Any Key> to terminate service."); Console.WriteLine(); Console.ReadKey(); // Close the ServiceHostBase to shutdown the service. svcHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); svcHost.Abort(); } }
protected override Binding CreateMetadataExchangeBinding() { return(MetadataExchangeBindings.CreateMexNamedPipeBinding()); }
public static void Main(string[] args) { string url = "http://localhost:8181/soap/helloservice"; ServiceHost serviceHost = null; try { serviceHost = new ServiceHost(typeof(HelloService), new Uri(url)); var smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(smb); serviceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNamePasswordValidator(); serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; serviceHost.AddServiceEndpoint(typeof(IHelloService), binding, string.Empty); serviceHost.Open(); var endpoint = serviceHost.Description.Endpoints.First(); Console.WriteLine("The Hello service is running and is listening on:"); Console.WriteLine("{0} ({1})", endpoint.Address.ToString(), endpoint.Binding.Name); Console.WriteLine("\nPress any key to stop the service."); Console.ReadKey(); } catch (Exception e) { Console.WriteLine(e); } finally { if (serviceHost != null) { if (serviceHost.State == CommunicationState.Faulted) { serviceHost.Abort(); } else { serviceHost.Close(); } } } }
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); } } }
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); } } }
internal void AddNamePipeEndpoints() { host.AddServiceEndpoint(typeof(IRestaurantService), new NetNamedPipeBinding(), NamedPipeServiceAddress); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), NamedPipeMexAddress); }
protected override void OnStart(string[] args) { try { serviceHost = new ServiceHost(typeof(ConvRatesService)); serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior()); NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None) { ReceiveTimeout = TimeSpan.FromSeconds(1) }; string serviceUrl = ConfigurationManager.AppSettings["ConvRatesServiceUrl"]; serviceHost.AddServiceEndpoint(typeof(IConvRate), netTcpBinding, serviceUrl); serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), serviceUrl + "mex"); serviceHost.Open(); ConvRatesProvider.GetInstance().Init(); log.Info("ConvRatesWinService host is UP."); } catch (Exception e) { log.Error("ConvRatesWinService OnStart failed:", e); } }
internal void AddHttpEndpoints() { host.AddServiceEndpoint(typeof(IRestaurantService), new BasicHttpBinding(), HttpServiceAddress); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), HttpMexAddress); }
private void InitializeServer() { BasicHttpBinding BasicBinding = new BasicHttpBinding(); BasicBinding.Name = "sonesBasic"; BasicBinding.Namespace = Namespace; BasicBinding.MessageEncoding = WSMessageEncoding.Text; BasicBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; BasicBinding.MaxBufferSize = 268435456; BasicBinding.MaxReceivedMessageSize = 268435456; BasicBinding.SendTimeout = new TimeSpan(1, 0, 0); BasicBinding.ReceiveTimeout = new TimeSpan(1, 0, 0); XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas(); readerQuotas.MaxDepth = 2147483647; readerQuotas.MaxStringContentLength = 2147483647; readerQuotas.MaxBytesPerRead = 2147483647; readerQuotas.MaxNameTableCharCount = 2147483647; readerQuotas.MaxArrayLength = 2147483647; BasicBinding.ReaderQuotas = readerQuotas; BasicHttpBinding StreamedBinding = new BasicHttpBinding(); StreamedBinding.Name = "sonesStreamed"; StreamedBinding.Namespace = Namespace; StreamedBinding.MessageEncoding = WSMessageEncoding.Text; StreamedBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; StreamedBinding.MaxReceivedMessageSize = 2147483647; StreamedBinding.MaxBufferSize = (UseStreaming == true) ? 4096 : 2147483647; StreamedBinding.SendTimeout = new TimeSpan(1, 0, 0, 0); StreamedBinding.ReceiveTimeout = new TimeSpan(1, 0, 0, 0); if (UseStreaming == true) { StreamedBinding.TransferMode = TransferMode.Streamed; } WebHttpBinding WebBinding = new WebHttpBinding(); WebBinding.Name = "sonesWeb"; WebBinding.Namespace = Namespace; WebBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; if (IsSecure) { BasicBinding.Security.Mode = BasicHttpSecurityMode.Transport; StreamedBinding.Security.Mode = BasicHttpSecurityMode.Transport; } RPCServiceContract ContractInstance = new RPCServiceContract(_GraphDS); _ServiceHost = new ServiceHost(ContractInstance, this.URI); _ServiceHost.Description.Namespace = Namespace; #region Streamed Contract _ServiceHost.AddServiceEndpoint(typeof(IStreamedService), StreamedBinding, this.URI.ToString() + "/streamed"); #endregion #region GraphDS API Contract _ServiceHost.AddServiceEndpoint(typeof(IGraphDS_API), BasicBinding, this.URI); #region json //ServiceEndpoint APIServiceJson = new ServiceEndpoint(APIContract, WebBinding, new EndpointAddress(this.URI.ToString() + "/json")); //APIServiceJson.Behaviors.Add(new WebScriptEnablingBehavior()); //_ServiceHost.AddServiceEndpoint(APIServiceJson); #endregion #endregion #region Type Services #region VertexTypeService _ServiceHost.AddServiceEndpoint(typeof(IVertexTypeService), BasicBinding, this.URI); #endregion #region VertexInstanceService _ServiceHost.AddServiceEndpoint(typeof(IVertexService), BasicBinding, this.URI); #endregion #region EdgeTypeService _ServiceHost.AddServiceEndpoint(typeof(IEdgeTypeService), BasicBinding, this.URI); #endregion #region EdgeInstanceService _ServiceHost.AddServiceEndpoint(typeof(IEdgeService), BasicBinding, this.URI); #endregion #endregion #region Metadata Exchange /* * When using automatic wsdl generation, there are errors when not using C# Visual Studio: * - (server side) Mono does not yet support wsdl generation * - Java Stub generation using Axis causes the server to hang up * - Some importers may not support multiple markup files * * Therefore, a static wsdl file is provided to the client. */ _MexServiceHost = new ServiceHost(typeof(MonoMEX), MexUri); _MexServiceHost.Description.Namespace = Namespace; Binding MexBinding = new WebHttpBinding(); MexBinding.Namespace = Namespace; _MexServiceHost.AddServiceEndpoint(typeof(IMonoMEX), MexBinding, MexUri); _MexServiceHost.Description.Endpoints[0].Behaviors.Add(new System.ServiceModel.Description.WebHttpBehavior()); #region auto generation #if __MonoCS__ #else ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior(); metadataBehavior.HttpGetEnabled = true; Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding(); mexBinding.Namespace = Namespace; _ServiceHost.Description.Behaviors.Add(metadataBehavior); ServiceEndpoint mexEndpoint = _ServiceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, mexBinding, "mex"); foreach (ServiceEndpoint endpoint in _ServiceHost.Description.Endpoints) { //export just one file endpoint.Behaviors.Add(new WsdlExtensions(new WsdlExtensionsConfig() { SingleFile = true })); } #endif #endregion #endregion }