这是我从你的问题中可以理解的:
- 您有 2 个 Windows 服务(为简单起见,Service1 和 Service2)
- Service1 托管 WCF 服务
- Service2 需要使用 WCF 服务的双向方法
如果这一切都是正确的,以下是你应该做的一些事情:
应将 WCF 服务配置为通过NetNamedPipes 进行连接,因为如那篇文章所述,
NetNamedPipeBinding 提供安全可靠的绑定,并针对机器上的通信进行了优化。
Service2需要在WCF服务中添加Service Reference,你可以找到怎么做here。
既然 Service1 知道 Service2(而 Service2 知道 Service1 绝对没有意义),您必须声明您的服务方法以允许双向通信。这是我所做的一个实现示例:
[ServiceContract(Namespace = "http://Your.Namespace", SessionMode = SessionMode.Required)]
public interface ICommunicator
{
[OperationContract(IsOneWay = false)]
string StartServer(string serverData);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class CommunicatorService : ICommunicator
{
public string StartServer(string serverData)
{
//example method that takes a string as input and returns another string
return "Hello!!!!";
}
}
编辑:添加客户端和服务器配置。但是,我必须告诉你,由于我遇到了多个不相关的 app.config 问题,因此客户端配置是通过代码完成的。
服务器 app.config:
<system.serviceModel>
<services>
<service behaviorConfiguration="MyNamespace.CommunicatorServiceBehavior" name="MyNamespace.CommunicatorService">
<endpoint address="" binding="netNamedPipeBinding" name="netNamedPipeCommunicator" contract="MyNamespace.ICommunicator">
</endpoint>
<endpoint address="mex" binding="mexNamedPipeBinding" name="mexNamedPipeCommunicator" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/CommunicatorService" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyNamespace.CommunicatorServiceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
客户代码:
private static ICommunicator Proxy;
ServiceEndpoint endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(ICommunicator)))
{
Address = new EndpointAddress("net.pipe://localhost/CommunicatorService"),
Binding = new NetNamedPipeBinding()
};
Proxy = (new DuplexChannelFactory<ICommunicator>(new InstanceContext(this), endpoint)).CreateChannel();
((IClientChannel)Proxy).Open();
public void StartServer(string serverData)
{
string serverStartResult = Proxy.StartServer(serverData); // calls the method I showed above
}