如何在 C# 中正确使用命名管道——多个连接、服务器娱乐等 [英] How to use named pipes in C# correctly -- several connections, server recreation etc

查看:243
本文介绍了如何在 C# 中正确使用命名管道——多个连接、服务器娱乐等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 C# 应用程序之间实现进程间通信.我决定使用命名管道并编写以下代码:

I need to implement an inter-process communication between C# applications. I decided to use named pipes and wrote the following code:

服务器

while (true)
{
    using (var server = new NamedPipeServerStream("some_pipe"))
    {
        server.WaitForConnection();
        using (var reader = new StreamReader(server))
        {
            string line = reader.ReadLine();
            MessageBox.Show(line);
        }
    }
}

客户

using (var client = new NamedPipeClientStream("some_pipe"))
{
    client.Connect();

    using (var writer = new StreamWriter(client))
    {
        writer.AutoFlush = true;
        writer.WriteLine(path);
        client.WaitForPipeDrain();
    }
}

我有以下问题:

  • 这个解决方案完全正确吗?您是否已经看到任何问题或错误?
  • 如果第二个客户端尝试连接到该服务器会发生什么?它会等待第一个客户端完成还是只是将其消息与另一个客户端的实例一起发送导致垃圾?
  • 我真的应该每次都创建 NamedPipeServerStream 类的另一个实例吗?如果我从 while (true) 循环中移动它的构造,它会给我一个异常无法访问封闭的管道".我怎样才能避免它?如果我无法避免它并且每次都应该重新创建这个对象,如果在客户端尝试连接它时没有 NamedPipeServerStream 会发生什么?
  • Is this solution correct at all? Is there any issues or bugs you already see?
  • What will happen if the second client will try to connect to this server? Will it wait for the first client to finish or just send its message along with another client's instance resulting in garbage?
  • Should I really create another instance of NamedPipeServerStream class every time? If I move its construction from the while (true) loop it gives me an exception "Cannot access a closed pipe". How can I avoid it? If I can't avoid it and should re-create this object every time, what will happen if there is no NamedPipeServerStream at the moment when client will try to connect to it?

推荐答案

这将不起作用.多个客户端仅连接到一个 NamedPipeServerStream 是一项不可用的功能.它带有...ServerStream"的名称具有误导性.管道是 1 对 1 连接.您必须有多个服务器实例为多个客户端提供相同的管道服务.此代码项目展示了如何实现服务器管道,可能会有所帮助你.

This will not work. Multiple clients connecting to just one NamedPipeServerStream is a feature not available. Its name with "...ServerStream" is misleading. Pipes are 1 to 1 connections. You must have multiple server instances serving the same pipe for many clients. This Code Project shows how to implement a Server Pipes and may help you.

这篇关于如何在 C# 中正确使用命名管道——多个连接、服务器娱乐等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆