C#命名隧道跨进程通信

在C#项目编写过程中,经常会遇到两个程序需要进行通信问题,如果两个程序在同一设备上运行,则可以选择命名隧道方式通信。
优点:
1.代码实现简单
2.通信可靠,不易出现两个程序失联
缺点:
1.通信过程需要自处理
2.多线程并发有数据丢失风险

具体实现demo如下

  1. server端
using System.IO.Pipes;
using System.Text;

namespace 命名管道通信
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建命名管道
            NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut);

            // 等待客户端连接
            pipeServer.WaitForConnection();

            while (true)
            {
                // 读取客户端发送的数据
                byte[] buffer = new byte[1024];
                int bytesRead = pipeServer.Read(buffer, 0, buffer.Length);
                string data = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received data: {0}", data);

                // 向客户端发送数据
                string response = "ok";
                byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(response);
                pipeServer.Write(responseBytes, 0, responseBytes.Length);
            }
            
            // 关闭管道
            pipeServer.Close();
        }
    }
}
  1. client端
using System.IO.Pipes;
using System.Text;

namespace 命名管道通信Client
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建命名管道客户端
            NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut);

            // 连接到管道服务器
            pipeClient.Connect();
            while (true)
            {
                // 向服务器发送数据
                string message = "Hello from client!";
                byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(message);
                pipeClient.Write(messageBytes, 0, messageBytes.Length);

                // 从服务器读取数据
                byte[] buffer = new byte[1024];
                int bytesRead = pipeClient.Read(buffer, 0, buffer.Length);
                string response = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received response: {0}", response);

                if ( Console.ReadLine()=="a") break;
            }
            

            // 关闭管道
            pipeClient.Close();
        }
    }
}

本次写的是连续通信,在实际项目中,可能需要按业务需求自行封装

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值