我有一个 Windows 服务和一个 GUI 需要相互通信。两者都可以随时发送消息。
我正在考虑使用 NamedPipes,但您似乎无法同时读取和写入流(或者至少我找不到涵盖这种情况的任何示例)。
是否可以通过单个 NamedPipe 进行这种双向通信? 或者我是否需要打开两个管道(一个来自 GUI->service,一个来自 service->GUI)?
最佳答案
使用 WCF,您可以使用双工命名管道
// 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();
}
}
}
创建客户端应用程序,在此示例中,Client 类实现了回调契约。
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");
}
}
关于c# - 与 Windows 命名管道 (.Net) 的异步双向通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16432813/