引用就不說明,直接貼上:app
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Configuration;
using System.Collections;tcp
public class WCFServiceHelper
{orm
private static List<ServiceHost> _ServiceHost = new List<ServiceHost>();接口
/// <summary>
/// 啓動WCF服務
/// </summary>
public static void ServiceStart()
{string
//配置的服務地址,本身配置
string WCFServiceAddress = ConfigurationManager.AppSettings["WCFServiceAddress"];it
/* 配置的格式如io
<appSettings>
<add key="WCFServiceAddress" value="net.tcp://127.0.0.1:8888"/>
</appSettings>class
*/配置
//獲取配置文件的服務名稱,就是那些接口,形式看具體需求去配foreach
/* 若是多個服務要逗號分隔開,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>
*/