Fra*_* B. 6 c# wcf client-server
语境:
我需要开发一个监视服务器来监视我们的一些应用程序(这些应用程序在c#中).所以我决定使用WCF开发系统,这似乎适合我的需求.
这些应用程序在启动时必须将自己注册到监视服务器.之后,监视服务器可以调用这些应用程序的Start或Stop方法.
一切都在同一台机器上完全执行,无需远程执行任何操作.
所以我开发了一个很好的原型,一切正常.每个应用程序将自己注册到监视服务器.
题:
ApplicationRegistrationService
(请参阅下面的代码)是监视服务的实现,由于ServiceBehavior
属性,它是一个单例实例.
这是我的问题:我想访问ApplicationRegistrationService
每个示例的内容,从我的服务器(ConsoleMonitoringServer
在示例中)连接的应用程序的数量.但是,我不知道如何实现这一目标.
我是否需要在我的服务器中创建一个通道,就像我在客户端(ConsoleClient
)中所做的那样,或者它是否有更好的方法来实现这一目标?
码:
出于此问题的目的,代码非常简化:
//The callback contract interface
public interface IApplicationAction
{
[OperationContract(IsOneWay = true)]
void Stop();
[OperationContract(IsOneWay = true)]
void Start();
}
[ServiceContract(SessionMode = SessionMode.Required,
CallbackContract = typeof(IApplicationAction))]
public interface IApplicationRegistration
{
[OperationContract]
void Register(Guid guid, string name);
[OperationContract]
void Unregister(Guid guid);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class ApplicationRegistrationService : IApplicationRegistration
{
//IApplicationRegistration Implementation
}
public class ApplicationAction : IApplicationAction
{
//IApplicationAction Implementation
}
Run Code Online (Sandbox Code Playgroud)
此示例的控制台应用程序
class ConsoleClient
{
static void Main(string[] args)
{
ApplicationAction actions = new ApplicationAction();
DuplexChannelFactory<IApplicationRegistration> appRegPipeFactory =
new DuplexChannelFactory<IApplicationRegistration>(actions,
new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/AppReg"));
IApplicationRegistration proxy = appRegPipeFactory.CreateChannel();
proxy.Register(Guid.Empty, "ThisClientName");
//Do stuffs
}
}
Run Code Online (Sandbox Code Playgroud)
此示例的控制台服务器
class ConsoleMonitoringServer
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(ApplicationRegistrationService),
new Uri[]{ new Uri("net.pipe://localhost")}))
{
host.AddServiceEndpoint(typeof(IApplicationRegistration),
new NetNamedPipeBinding(), "AppReg");
host.Open();
//Wait until some write something in the console
Console.ReadLine();
host.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后,我找到答案,这很容易.我只需要创建服务实例并将引用传递给ServiceHost的构造函数.
所以我需要替换以下代码:
using (ServiceHost host = new ServiceHost(typeof(ApplicationRegistrationService),
new Uri[]{ new Uri("net.pipe://localhost")}))
Run Code Online (Sandbox Code Playgroud)
通过:
ApplicationRegistrationService myService = new ApplicationRegistrationService();
using (ServiceHost host = new ServiceHost(myService,
new Uri[]{ new Uri("net.pipe://localhost")}))
Run Code Online (Sandbox Code Playgroud)