引用就不说明,直接贴上:
using System;
using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceModel;using System.Configuration;using System.Collections;public class WCFServiceHelper
{ private static List<ServiceHost> _ServiceHost = new List<ServiceHost>();/// <summary>
/// 启动WCF服务 /// </summary> public static void ServiceStart() {//配置的服务地址,自己配置
string WCFServiceAddress = ConfigurationManager.AppSettings["WCFServiceAddress"];/* 配置的格式如
<appSettings>
<add key="WCFServiceAddress" value="net.tcp://127.0.0.1:8888"/> </appSettings>*/
//获取配置文件的服务名称,就是那些接口,形式看具体需求去配
/* 如果多个服务要逗号分隔开,My.IService1,My.IService2服务接口,My.Service.Service1,My.Service.Service2服务实现
<WCFServices>
<add key="My.IService1,My.IService2" value="My.Service.Service1,My.Service.Service2"/>多个就继续往下配置
</WCFServices>
*/
IDictionary WCFDict = ConfigurationManager.GetSection("WCFServices") as IDictionary;//获取自定义的节点 if (WCFDict != null) { string ServiceName = string.Empty; NetTcpBinding Binding; string[] Services; string[] IServices; ServiceHost host;foreach (DictionaryEntry dict in WCFDict)//这里面遍历绑定服务
{ServiceName = dict.Value.ToString();
Services = ServiceName.Split(',')[0].Split('.'); IServices = dict.Key.ToString().Split(',')[0].Split('.');Binding = new NetTcpBinding("TcpSet");//绑定协议
Binding.ReceiveTimeout = new TimeSpan(0, 30, 0);Binding.Security.Mode = SecurityMode.None;
host = new ServiceHost(Type.GetType(ServiceName));
host.AddServiceEndpoint(Type.GetType(dict.Key.ToString()), Binding, string.Format("{0}/{1}", WCFServiceAddress, Services[Services.Length - 1]));try
{ host.Open();Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(string.Format("{0}启动成功", string.Format("{0}/{1}", WCFServiceAddress, Services[Services.Length - 1]))); _ServiceHost.Add(host); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(string.Format("{0}启动失败,失败原因:{1}", string.Format("{0}/{1}", WCFServiceAddress, Services[Services.Length - 1]),exception.ToString())); } } } }/// <summary>
/// 停止WCF服务 /// </summary> public static void ServiceStop() { foreach (ServiceHost host in _ServiceHost) { host.Close(); } } }/*绑定的配置
<system.serviceModel>
<bindings> <netTcpBinding> <binding name="TcpSet" maxBufferSize="2147483647" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxConnections="100000"> <readerQuotas maxDepth="32" maxStringContentLength="2147483647 " maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384"/> </binding> </netTcpBinding> </bindings> </system.serviceModel>*/