C# 命名管道NamedPipeServerStream使用

NamedPipeServerStream 是 .NET Framework 和 .NET Core 中提供的一个类,用于创建和操作命名管道的服务器端。命名管道是一种在同一台计算机上或不同计算机之间进行进程间通信的机制。

命名管道允许两个或多个进程通过共享的管道进行通信。其中一个进程充当服务器,创建管道并等待客户端连接。其他进程充当客户端,连接到服务器创建的管道,并通过管道进行数据交换。

NamedPipeServerStream 类提供了创建命名管道服务器端的功能。它允许你指定管道的名称、方向(输入、输出或双向)和一些其他选项。一旦服务器端创建并等待连接,客户端可以使用 NamedPipeClientStream 类连接到该管道,并进行数据交换。

本次只演示客户端-服务端通讯:

服务端: 

/// <summary>
    /// 服务端
    /// </summary>
    public partial class FrmTest : Form
    {
        private NamedPipeServerStream pipeServer;
        volatile bool _receive = true;
        public FrmTest()
        {
            InitializeComponent();

            // 连接到命名管道
            pipeServer = new NamedPipeServerStream("Test", PipeDirection.In);
            Thread thread = new Thread(() =>
            {
                while (_receive)
                {
                    try
                    {
                        if(!pipeServer.IsConnected)
                        {
                            Console.WriteLine("等待客户端连接。。。");
                            pipeServer.WaitForConnection();
                            Console.WriteLine("客户端已连接。。。");
                        }

                        // 读取字节大小
                        byte[] sizeBuffer = new byte[sizeof(int)];
                        pipeServer.Read(sizeBuffer, 0, sizeBuffer.Length);
                        int messageSize = BitConverter.ToInt32(sizeBuffer, 0);
                        // 消息内容
                        byte[] responseBytes = new byte[messageSize];
                        Console.WriteLine("等待客户端发送消息。。。");
                        int bytesRead = pipeServer.Read(responseBytes, 0, responseBytes.Length);
                        Console.WriteLine("客户端已发送消息。。。");
                        string response = Encoding.UTF8.GetString(responseBytes, 0, bytesRead);
                        this.ExecBeginInvoke(() =>
                        {
                            this.richTextBox1.AppendText(DateTime.Now.ToStringFromDateTime() + ":\r\n" + response + "\r\n");
                        });

                        pipeServer.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex.Message+"\r\n"+ex.StackTrace);
                    }
                    finally
                    {
                    }
                }
            });
            thread.Start();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
        }


        private void FrmTest_FormClosing(object sender, FormClosingEventArgs e)
        {
            _receive = false;
            if (pipeServer.IsConnected)
            {
                pipeServer.Disconnect();
            }
            // 关闭管道
            pipeServer.Close();
            this.Dispose();
            Application.ExitThread();
            Application.Exit();
            Process.GetCurrentProcess().Kill();
        }

        private void FrmTest_FormClosed(object sender, FormClosedEventArgs e)
        {
        }
    }

客户端: 

/// <summary>
    /// 客户端
    /// </summary>
    public partial class FrmTest : Form
    {
        public FrmTest()
        {
            InitializeComponent();

        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            string msg = this.richTextBox1.Text;
            // 连接到命名管道服务器
            using (NamedPipeClientStream clientStream = new NamedPipeClientStream(".", "Test", PipeDirection.Out))
            {
                try
                {
                    Console.WriteLine("等待连接到服务器");
                    clientStream.Connect(5000);
                    Console.WriteLine("已连接到服务器");

                    // 向服务器发送消息
                    string message = msg;
                    byte[] messageBytes = Encoding.UTF8.GetBytes(message);
                    byte[] msgSize = Encoding.UTF8.GetBytes(messageBytes.Length.ToString());
                    clientStream.Write(msgSize, 0, msgSize.Length);
                    clientStream.Write(messageBytes, 0, messageBytes.Length);
                    Console.WriteLine("已发送消息至服务器");
                }
                catch(Exception ex)
                {
                    Console.WriteLine("连接超时。。。");
                }
                finally
                {
                    clientStream.Close();
                }
            }
        }
        private void FrmTest_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
            Application.ExitThread();
            Application.Exit();
        }
    }

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你的问题是关于 C# 管道通信中的命名管道,我会为你进行解答。 首先,命名管道是一种在本地计算机或网络上进行进程间通信的机制。它允许一个进程向另一个进程发送数据或接收数据。在 C# 中,我们可以使用命名管道来实现进程间通信。 在使用命名管道之前,我们需要先创建一个命名管道。可以使用 .NET Framework 中的 `NamedPipeServerStream` 类来创建一个命名管道。以下是创建命名管道的代码示例: ```csharp // 创建命名管道 NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut); ``` 上面的代码将创建一个名为 "testpipe" 的命名管道,并指定了管道的方向为双向。 接下来,我们可以使用 `NamedPipeServerStream` 类的 `WaitForConnection` 方法等待客户端连接到管道。一旦有客户端连接,我们就可以使用 `NamedPipeServerStream` 类的 `Read` 和 `Write` 方法来进行数据的读写。 以下是一个简单的命名管道通信示例: ```csharp // 创建命名管道 NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut); // 等待客户端连接 pipeServer.WaitForConnection(); // 从客户端读取数据 byte[] buffer = new byte[1024]; int bytesRead = pipeServer.Read(buffer, 0, buffer.Length); string data = Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine("Received data: " + data); // 向客户端发送数据 string response = "Hello, client!"; byte[] responseBuffer = Encoding.UTF8.GetBytes(response); pipeServer.Write(responseBuffer, 0, responseBuffer.Length); // 关闭管道 pipeServer.Close(); ``` 在上面的代码中,我们首先创建了一个名为 "testpipe" 的命名管道。然后,我们使用 `WaitForConnection` 方法等待客户端连接,并读取客户端发送的数据。接着,我们向客户端发送响应数据,并关闭管道。 总的来说,使用命名管道可以很方便地实现进程间通信。在实际应用中,我们可以根据需要对命名管道进行配置,以实现更复杂的通信逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值