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();
        }
    }

相关推荐

  1. # .NET Framework中使用命名管道进行进程间通信

    2024-01-28 10:32:01       60 阅读
  2. C++中变量的使用细节和命名方案

    2024-01-28 10:32:01       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-28 10:32:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-28 10:32:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-28 10:32:01       82 阅读
  4. Python语言-面向对象

    2024-01-28 10:32:01       91 阅读

热门阅读

  1. Mysql的备份以及恢复

    2024-01-28 10:32:01       49 阅读
  2. wsl装ubuntu的home目录在哪,如何更改home?

    2024-01-28 10:32:01       48 阅读
  3. 优雅的管理你的docker容器【Docker Swarm篇】

    2024-01-28 10:32:01       45 阅读
  4. mysql-线上常用运维sql

    2024-01-28 10:32:01       63 阅读
  5. 晶体管控制和继电器控制的差异

    2024-01-28 10:32:01       53 阅读
  6. Bootstrap5之icons字体图标及简单布局案例

    2024-01-28 10:32:01       53 阅读
  7. 04-Nacos-服务注册基于spring boot实现

    2024-01-28 10:32:01       66 阅读
  8. 【嵌入式——C++】模板

    2024-01-28 10:32:01       61 阅读