服务接口:
namespace WCFService
{
[ServiceContract]
public interface IServiceWindow
{
[OperationContract(IsOneWay=false)]
string GetCurrentTime();
}
}
服务实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFService
{
public class ServiceWindow:IServiceWindow
{
#region IServiceWindow 成员
public string GetCurrentTime()
{
return string.Format("Window Server Time:{0}", DateTime.Now.ToString());
}
#endregion
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service behaviorConfiguration="WCFService.ServiceWindowBehavior"
name="WCFService.ServiceWindow">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/ServiceWindow/"/>
</baseAddresses>
</host>
<endpoint address="/Address1"
binding="basicHttpBinding"
contract="WCFService.IServiceWindow"/>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services >
<behaviors>
<serviceBehaviors>
<behavior name="WCFService.ServiceWindowBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
public void Start()
{
ServiceHost host = new ServiceHost(typeof(ServiceWindow));
host.Open();
}
private void btnStart_Click(object sender, EventArgs e)
{
Start();
}
1. 启动服务窗体
2. 客户端添加服务引用
ServiceWindow.ServiceWindowClient myHost3 = new WCFTest.ServiceWindow.ServiceWindowClient();
Console.WriteLine( myHost3.GetCurrentTime());
结果:
1. 服务接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace ConsoleService
{
[ServiceContract]
public interface IServiceConsole
{
[OperationContract(IsOneWay=false)]
string GetCurrentTime();
}
}
2. 服务实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace ConsoleService
{
public class ServiceConsole:IServiceConsole
{
#region IServiceWindow 成员
public string GetCurrentTime()
{
//ConsoleService.ServiceConsole
return string.Format("Console Server Time:{0}", DateTime.Now.ToString());
}
#endregion
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service behaviorConfiguration="ConsoleService.ServiceConsoleBehavior"
name="ConsoleService.ServiceConsole">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9000/ServiceConsole/"/>
</baseAddresses>
</host>
<endpoint address="/Address2"
binding="basicHttpBinding"
contract="ConsoleService.IServiceConsole"/>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services >
<behaviors>
<serviceBehaviors>
<behavior name="ConsoleService.ServiceConsoleBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
static void Main(string[] args)
{
ServiceHost myHost = new ServiceHost(typeof(ServiceConsole));
myHost.Open();
Console.Read();
myHost.Close();
}
1. 服务接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WindowsService
{
[ServiceContract]
interface IServiceTest
{
[OperationContract(IsOneWay=false)]
string GetCurrentTime();
}
}
2. 服务实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WindowsService
{
class ServiceTest:IServiceTest
{
#region IServiceWindowService 成员
public string GetCurrentTime()
{
Console.WriteLine("Receive call {0}", DateTime.Now);
return string.Format("Console Server Time:{0}", DateTime.Now.ToString());
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
namespace WindowsService
{
public partial class ServiceTestWindowService : ServiceBase
{
private ServiceHost serviceHost = null;
public ServiceTestWindowService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(ServiceTest));
serviceHost.Open();
}
protected override void OnStop()
{
if(serviceHost!=null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
namespace WindowsService
{
[RunInstaller(true)]
public partial class Installer1 : Installer
{
private ServiceProcessInstaller process;
private ServiceInstaller service;
public Installer1()
{
InitializeComponent();
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "WCFWindowsServiceSample";
Installers.Add(process);
Installers.Add(service);
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="WindowsService.ServiceTest" behaviorConfiguration="ConsoleService.ServiceConsoleBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9002/WindowService/ServiceTest"/>
</baseAddresses>
</host>
<!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/ServiceModelSamples/service -->
<endpoint address=""
binding="wsHttpBinding"
contract="WindowsService.IServiceTest" />
<!-- the mex endpoint is explosed at http://localhost:8000/ServiceModelSamples/service/mex -->
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ConsoleService.ServiceConsoleBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
1. 命令行安装
installUtil 程序名称
installutil 程序名称 /u
2. 服务启动
如何调ServiceWindowService.ServiceTestClient testClient = new WCFTest.ServiceWindowService.ServiceTestClient();
l 补充说明:
ServiceHost 不一定必须在在windows 服务的 OnStart中实现。OnStart
下面例子演示了这种实现。
l Service中实现ServiceHost
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Xml;
using TPRIBPM.Base.Tools;
namespace TPRIBPM.Foundation.PWService
{
public class WCFService
{
private ServiceHost host;
private Uri serverUrl;
private TPRIBPM.Foundation.PWDB.PWDBDataContext dataContext ;
PowerService pwser;
//http://localhost:7654/PWDB/
public WCFService(Uri serverUrl)
{
try
{
string connectionString = MyConfig.getConnection("myconstring");
if (!string.IsNullOrEmpty(connectionString))
{
dataContext = new TPRIBPM.Foundation.PWDB.PWDBDataContext(connectionString);
}
else
{
dataContext = new TPRIBPM.Foundation.PWDB.PWDBDataContext();
}
dataContext.SubmitChanges();
MyLog.writeInfo("数据库连接成功:" + dataContext.Connection.ConnectionString);
this.serverUrl = serverUrl;
pwser = new PowerService(dataContext);
host = new ServiceHost(pwser, serverUrl);
host.Closed += new EventHandler(host_Closed);
host.Opened += new EventHandler(host_Opened);
host.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(host_UnknownMessageReceived);
host.Faulted += new EventHandler(host_Faulted);
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(behavior);
System.ServiceModel.BasicHttpBinding bh = new BasicHttpBinding();
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
quotas.MaxStringContentLength = 7000000;
bh.ReaderQuotas = quotas;
bh.MaxReceivedMessageSize = 7000000;
host.AddServiceEndpoint(typeof(IPowerService), bh, "PW/");
}
catch (System.Exception ex)
{
MyLog.writeError(ex.Message);
throw new MyException(ex.Message);
}
}
void host_Faulted(object sender, EventArgs e)
{
MyLog.writeError("WCF-Faulted");
}
void host_UnknownMessageReceived(object sender, UnknownMessageReceivedEventArgs e)
{
MyLog.writeError("WCF-UnknownMessageReceived");
}
void host_Opened(object sender, EventArgs e)
{
MyLog.writeInfo("WCF服务已启动,url:" + host.BaseAddresses[0].AbsoluteUri.ToString());
}
void host_Closed(object sender, EventArgs e)
{
MyLog.writeInfo("WCF服务已停止");
}
public int? open()
{
try
{
if (host.State == CommunicationState.Created)
{
host.Open();
return null ;
}
return 1;
}
catch (System.Exception ex)
{
MyLog.writeError(ex.Message);
throw new MyException(ex.Message);
}
}
public int? close()
{
if (host.State == CommunicationState.Opened)
{
host.Close();
return null;
}
else
{
return 1;
}
}
}
}
l windows服务类中调用serverhost的实现类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Configuration;
using TPRIBPM.Foundation.PWService;
using TPRIBPM.Base.Tools;
namespace TPRIBPM.Foundation.WinServicePWServer
{
/***********************************************************************
* Module: 权限服务的Windows Service包装
* Author: [email protected]
* Create Date: 2009/7/27
* Summary:
***********************************************************************/
public partial class TPRIBPMPWService : ServiceBase
{
/// <summary>
/// PW的WCFService
/// </summary>
private WCFService wcfser;
public TPRIBPMPWService()
{
InitializeComponent();
}
/// <summary>
/// 启动
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
string urlAddress = ConfigurationManager.AppSettings["wcfserviceurl"];
wcfser = new TPRIBPM.Foundation.PWService.WCFService(new Uri(urlAddress));
int? v = wcfser.open();
if (v == null)
{
MyDebug.write("服务已启动");
}
}
/// <summary>
/// 关闭
/// </summary>
protected override void OnStop()
{
close();
}
/// <summary>
/// 关闭方法
/// </summary>
void close()
{
if (wcfser != null)
{
int? v = wcfser.close();
if (v == null)
{
MyDebug.write("服务已停止");
}
}
}
}
}