声明提供服务的主机与服务名:
private static ServiceHost _host;
private static readonly string strServiceName = "/DataService";
启动服务端,默认端口8000:
/// <summary>
/// 启动系统主服务。
/// </summary>
/// <param name="port">端口</param>
private static ServiceHost _host;
private static void StartService(int port)
{
string strHostIPAddress = "localhost";
UriBuilder builder = new UriBuilder(System.Uri.UriSchemeHttp, strHostIPAddress, port, strServiceName);
_host = new ServiceHost(typeof(Common.DataService.DataService), builder.Uri);
#if DEBUG
builder.Scheme = Uri.UriSchemeHttp;
builder.Port = port;
builder.Path = strServiceName + "/mex";
Uri mexAddress = builder.Uri;
ServiceMetadataBehavior smb = _host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb != null)
{
smb.HttpGetEnabled = true;
smb.HttpGetUrl = mexAddress;
}
else
{
smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.HttpGetUrl = mexAddress;
_host.Description.Behaviors.Add(smb);
}
#endif
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);
}
_host.AddServiceEndpoint(typeof(Common.DataInterface.DB.IDataBaseService), DataServiceHttpBinding, "");
#if DEBUG
_host.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), mexAddress);
#endif
_host.Open();
}
private static BasicHttpBinding DataServiceHttpBinding
{
get
{
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
binding.TransferMode = TransferMode.Buffered;
binding.MessageEncoding = WSMessageEncoding.Mtom;
binding.MaxReceivedMessageSize = 2147483647;
binding.MaxBufferPoolSize = 524288;
binding.MaxBufferSize = 2147483647;
binding.OpenTimeout = new TimeSpan(0, 1, 0);
binding.CloseTimeout = new TimeSpan(0, 1, 0);
binding.SendTimeout = new TimeSpan(0, 1, 0);
binding.ReceiveTimeout = new TimeSpan(0, 1, 0);
binding.AllowCookies = false;
binding.BypassProxyOnLocal = false;
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.TextEncoding = Encoding.UTF8;
binding.UseDefaultWebProxy = true;
return binding;
}
}
停止服务:
private static void StopService()
{
if (_host.State != CommunicationState.Closed)
_host.Close();
}