与Windows命名管道(.Net)的异步双向通信

ste*_*ook 16 .net c# windows asynchronous named-pipes

我有一个需要相互通信的Windows服务和GUI.可以随时发送消息.

我期待在使用了NamedPipes,但似乎你不能阅读和在同一时间写入流(或至少我不能找到覆盖这种情况下,任何的例子).

是否可以通过一个NamedPipe进行这种双向通信?或者我需要打开两个管道(一个来自GUI->服务,一个来自service-> GUI)?

Roh*_*est 27

使用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();
}
Run Code Online (Sandbox Code Playgroud)

实施服务

[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();
    }
}
Run Code Online (Sandbox Code Playgroud)

托管服务

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

创建客户端应用程序,在此示例中,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");
    }
}
Run Code Online (Sandbox Code Playgroud)