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

标签 c# .net windows asynchronous named-pipes

我有一个 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/

相关文章:

c# - 如何使用 Linq "NOT IN"

asp.net - 如何将旧的.NET项目切换到Linux?

C#:如何在强制不同编码的同时调用方法?

C# Roslyn 编译 - 在动态编译的代码中使用 Nuget 包 - 编译但在运行时抛出异常(无法加载文件或程序集)

c# - ID3v2 C# 编写源代码?

在 Windows 中使用 Makefile 编译 C 源代码

c++ - 保持窗口始终在顶部——包括菜单 (win32)

c# - 有没有更简单的方法来使用未知类型进行类型转换?

c# - 如何调用嵌套的异步方法

c# - 如何自动加载 Roslyn 分析器(无代码修复)