异步与Windows命名管道的双向沟通(.NET) [英] Async two-way communication with Windows Named Pipes (.Net)
问题描述
我具有需要彼此通信的窗口服务和GUI。这两者都可以随时发送邮件。
I have a windows service and a GUI that need to communicate with each other. Either can send messages at any time.
我期待在使用了NamedPipes,但似乎你不能阅读和放大器;同时写入流(或至少我不能找到覆盖这种情况下,任何的例子)。
I'm looking at using NamedPipes, but it seems that you cant read & write to the stream at the same time (or at least I cant find any examples that cover this case).
是否有可能通过单NamedPipe做这样的双向通信的?
或者我需要打开两个管道(一个来自GUI的>服务,一个来自服务 - > GUI)?
Is it possible to do this kind of two-way communication via a single NamedPipe? Or do I need to open two pipes (one from GUI->service and one from service->GUI)?
推荐答案
使用WCF可以使用命名管道复式
Using WCF you can use duplex named pipes
// Create a contract that can be used as a callback
public interface IMyCallbackService
{
[OperationContract(IsOneWay = true)]
void NotifyClient();
}
// Define your service contract and specify the callback contract
[ServiceContract(CallbackContract = typeof(IMyCallbackService))]
public interface ISimpleService
{
[OperationContract]
string ProcessData();
}
实现服务
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class SimpleService : ISimpleService
{
public string ProcessData()
{
// Get a handle to the call back channel
var callback = OperationContext.Current.GetCallbackChannel<IMyCallbackService>();
callback.NotifyClient();
return DateTime.Now.ToString();
}
}
主机服务
class Server
{
static void Main(string[] args)
{
// Create a service host with an named pipe endpoint
using (var host = new ServiceHost(typeof(SimpleService), new Uri("net.pipe://localhost")))
{
host.AddServiceEndpoint(typeof(ISimpleService), new NetNamedPipeBinding(), "SimpleService");
host.Open();
Console.WriteLine("Simple Service Running...");
Console.ReadLine();
host.Close();
}
}
}
创建客户端应用程序,在本实施例的客户端类实现回叫合同
Create the client application, in this example the Client class implements the call back contract.
class Client : IMyCallbackService
{
static void Main(string[] args)
{
new Client().Run();
}
public void Run()
{
// Consume the service
var factory = new DuplexChannelFactory<ISimpleService>(new InstanceContext(this), new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/SimpleService"));
var proxy = factory.CreateChannel();
Console.WriteLine(proxy.ProcessData());
}
public void NotifyClient()
{
Console.WriteLine("Notification from Server");
}
}
这篇关于异步与Windows命名管道的双向沟通(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!