找回密码
 立即注册
首页 业界区 安全 推荐一款基于.NET的进程间数据交互经典解决方案 ...

推荐一款基于.NET的进程间数据交互经典解决方案

姥恫 3 小时前
在前面的文章中,我们介绍了基于Remoting,共享内存等技术的进程间通信方案,今天介绍一款基于.NET的进程间数据交互经典解决方案-管道(Pipes),仅供学习分享使用,如有不足之处,还请指正。
1.png

 
管道概述

 
在C#中,管道(Pipes)是一种进程间通信(IPC)机制,允许不同进程进行数据传输,位于System.IO.Pipes命名空间。C#提供了两种类型的管道:匿名管道和命名管道,分别适用于不同场景:

  • 匿名管道:匿名管道在本地计算机上提供进程间通信。 它们提供的功能比命名管道少,但也需要更少的开销。 可以使用匿名管道来简化本地计算机上的进程间通信。 不能使用匿名管道通过网络进行通信。
  • 命名管道:命名管道提供管道服务器与一个或多个管道客户端之间的进程间通信。 它们提供的功能比匿名管道更多,这些管道在本地计算机上提供进程间通信。 命名管道支持通过网络和多个服务器实例、基于消息的通信和客户端模拟进行全双工通信,这样连接进程就可以在远程服务器上使用自己的权限集。
 
匿名管道

 
匿名管道功能比较少,具有如下特点:

  • 匿名管道只能在单一计算机上进行通信,不能跨服务器进行通信。
  • 匿名管道只适于父子进程,不适于两个相关独立无任何关系的进程。
  • 匿名管道只支持单向传输,不支持双击传输。
匿名管道通过AnonymousPipeServerStream实现服务端,AnonymousPipeClientStream实现客户端,服务端和客户端可以分别进行接收(PipeDirection.In)或输出数据(PipeDirection.Out),但不是既接收又发送数据(PipeDirection.InOut)。
 
服务端

 
在本实例中,服务端是一个WinForm可执行程序【DemoAnonymousPipeServer】,用于接收客户端发送的数据,首先定义一个AnonymousPipeServer类,用于封装匿名管道服务端(AnonymousPipeServerStream)的操作。如下所示:
 
  1. using System.IO.Pipes;
  2. namespace DemoPipe.Common
  3. {
  4.     /// <summary>
  5.     /// 匿名管道帮助类
  6.     /// </summary>
  7.     public class AnonymousPipeServer:IDisposable
  8.     {
  9.         private AnonymousPipeServerStream pipeServerStream;
  10.         private CancellationTokenSource cts;
  11.         private CancellationToken token;
  12.         public Action<string> Received;
  13.         private string clientHandle;
  14.         public string ClientHandle
  15.         {
  16.             get { return clientHandle; }
  17.             set { clientHandle = value; }
  18.         }
  19.         private Task receiveTask;
  20.         public AnonymousPipeServer()
  21.         {
  22.             pipeServerStream = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
  23.             this.clientHandle = pipeServerStream.GetClientHandleAsString();
  24.             cts = new CancellationTokenSource();
  25.             token = cts.Token;
  26.         }
  27.         public void BeginReceive()
  28.         {
  29.             receiveTask = Task.Run(() =>
  30.             {
  31.                 using (StreamReader sr = new StreamReader(pipeServerStream))
  32.                 {
  33.                     while (!token.IsCancellationRequested)
  34.                     {
  35.                         try
  36.                         {
  37.                             string? msg = sr.ReadLine();
  38.                             if (!string.IsNullOrEmpty(msg))
  39.                             {
  40.                                 Received?.Invoke($"[{ClientHandle}]{msg}");
  41.                             }
  42.                         }
  43.                         catch (Exception ex)
  44.                         {
  45.                             Console.WriteLine(ex.Message);
  46.                             Console.WriteLine(ex.StackTrace);
  47.                         }
  48.                         finally
  49.                         {
  50.                             Task.Delay(500);
  51.                         }
  52.                     }
  53.                 }
  54.             });
  55.         }
  56.         /// <summary>
  57.         /// 资源释放
  58.         /// </summary>
  59.         public void Dispose()
  60.         {
  61.             this.cts.Cancel();
  62.             if (pipeServerStream != null)
  63.             {
  64.                 pipeServerStream.DisposeLocalCopyOfClientHandle();
  65.                 pipeServerStream.Close();
  66.                 pipeServerStream.Dispose();
  67.             }
  68.         }
  69.     }
  70. }
复制代码
 
在上述代码中,服务端通过StreamReader实现对流的读取,用于不断的接收数据,如接收到数据,则调用输出的Received委托方法。接下来,FrmMain页面实例化AnonymousPipeServer,并订阅Received委托方法,当接收到数据时,触发此方法,并将接收到的数据显示在UI页面上。
由于匿名管道只支持父子进程,所以在FrmMain页面打开子进程客户端,并将客户端句柄传递给客户端,用于初始化客户端对象。如下所示:
 
  1. using DemoPipe.Common;
  2. using System.Diagnostics;
  3. namespace DemoAnonymousPipeServer
  4. {
  5.     public partial class FrmMain : Form
  6.     {
  7.         private AnonymousPipeServer server;
  8.         private Process client;
  9.         public FrmMain()
  10.         {
  11.             InitializeComponent();
  12.             server = new AnonymousPipeServer();
  13.             this.lblClientHandle.Text = server.ClientHandle;
  14.             server.Received += new Action<string>((string msg) =>
  15.             {
  16.                 this.txtReceiveMsg.Invoke(() =>
  17.                 {
  18.                     this.txtReceiveMsg.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}:{msg}\r\n");
  19.                 });
  20.             });
  21.             server.BeginReceive();
  22.         }
  23.         private void btnOpenClient_Click(object sender, EventArgs e)
  24.         {
  25.             string clientName = "DemoAnonymousPipeClient.exe";
  26.             if (Process.GetProcessesByName(clientName).Length < 1)
  27.             {
  28.                 client = new Process();
  29.                 client.StartInfo.FileName = clientName;
  30.                 client.StartInfo.Arguments = server.ClientHandle;
  31.                 client.StartInfo.UseShellExecute = false;
  32.                 client.Start();
  33.             }
  34.         }
  35.     }
  36. }
复制代码
 
客户端

 
在本示例中,客户端是一个WinForm可执行程序【DemoAnonymousPipeClient】,用于和服务端建立连接,并发送数据到服务端,首先创建AnonymousPipeClient类,用于封装对匿名管道客户端AnonymousPipeClientStream的操作。如下所示:
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO.Pipes;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace DemoPipe.Common
  8. {
  9.     public class AnonymousPipeClient:IDisposable
  10.     {
  11.         private PipeStream pipeClientStream;
  12.         private string pipeHandle;
  13.         private StreamWriter streamWriter;
  14.         public AnonymousPipeClient(string pipeHandle)
  15.         {
  16.             this.pipeHandle = pipeHandle;
  17.             pipeClientStream = new AnonymousPipeClientStream(PipeDirection.Out, this.pipeHandle);
  18.             this.streamWriter = new StreamWriter(pipeClientStream);
  19.             this.streamWriter.AutoFlush = true;
  20.         }
  21.         public void Send(string msg)
  22.         {
  23.             try
  24.             {
  25.                 this.streamWriter.WriteLine(msg);
  26.                 pipeClientStream.WaitForPipeDrain();
  27.             }
  28.             catch (IOException ex)
  29.             {
  30.                 Console.WriteLine(ex.Message);
  31.                 Console.WriteLine(ex.StackTrace);
  32.             }
  33.         }
  34.         public void Dispose()
  35.         {
  36.             if (this.streamWriter != null)
  37.             {
  38.                 this.streamWriter.Close();
  39.                 this.streamWriter.Dispose();
  40.             }
  41.             if (pipeClientStream != null)
  42.             {
  43.                 pipeClientStream.Close();
  44.                 pipeClientStream.Dispose();
  45.             }
  46.         }
  47.     }
  48. }
复制代码
 
在上述代码中,客户端通过StreamWriter实现对流的写入, 用于将UI页面用户输入的信息发送到服务端。接下来在FrmMain页面中创建AnonymousPipeClient实例,并传入父进程传递来的句柄。如下所示:
 
  1. using DemoPipe.Common;
  2. namespace DemoAnonymousPipeClient
  3. {
  4.     public partial class FrmMain : Form
  5.     {
  6.         private AnonymousPipeClient client;
  7.         public FrmMain()
  8.         {
  9.             InitializeComponent();
  10.             this.txtClientHandle.Text = PipeInstance.PipeHandle;
  11.         }
  12.         private void btnSend_Click(object sender, EventArgs e)
  13.         {
  14.             try
  15.             {
  16.                 string msg = this.txtSendMsg.Text;
  17.                 if (!string.IsNullOrEmpty(msg))
  18.                 {
  19.                     client.Send(msg);
  20.                 }
  21.             }
  22.             catch (Exception ex)
  23.             {
  24.                 Console.WriteLine(ex.Message);
  25.                 Console.WriteLine(ex.StackTrace);
  26.             }
  27.         }
  28.         private void btnInit_Click(object sender, EventArgs e)
  29.         {
  30.             try
  31.             {
  32.                 string clientHandle = this.txtClientHandle.Text;
  33.                 client = new AnonymousPipeClient(clientHandle);
  34.                 MessageBox.Show("Init success.","Info",MessageBoxButtons.OK,MessageBoxIcon.Information);
  35.             }
  36.             catch (Exception ex)
  37.             {
  38.                 Console.WriteLine(ex.Message);
  39.                 Console.WriteLine(ex.StackTrace);
  40.             }
  41.         }
  42.     }
  43. }
复制代码
 
实例演示

 
由于客户端以子进程的方式启动,在Visual Studio中启动时只需要启动服务端一个项目,可以在解决方案右键打开“配置启动项”对话框,如下所示:
 
2.png

 
运行实例效果如下所示:
 
3.gif

 
命名管道

 
命名管道相对于匿名管道,功能较多,具有如下特点:

  • 命名管道支持跨服务进程间通信
  • 命名管道支持多管道通信。
  • 命名管道支持单向通信和双向通信。
 
命名管道通过NamedPipeServerStream实现服务端,NamedPipeClientStream实现客户端,服务端和客户端可以分别进行接收(PipeDirection.In)或输出数据(PipeDirection.Out),也支持既接收又发送数据(PipeDirection.InOut)。但需要注意管道资源的占用问题。
 
服务端

 
在本示例中,服务端采用WinForm的形式【DemoNamedPipeServer】,它用于接收数据和发送数据。首先创建NamedPipeServer类,用于封装NamedPipeServerStream的操作。如下所示:
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO.Pipes;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace DemoPipe.Common
  8. {
  9.     public class NamedPipeServer:IDisposable
  10.     {
  11.         private readonly int NUMOFTHREADS=4;
  12.         private string pipeName;
  13.         private NamedPipeServerStream pipeServerStream;
  14.         private StreamWriter streamWriter;
  15.         public Action<string> Received;
  16.         private StreamReader streamReader;
  17.         public NamedPipeServer(string pipeName)
  18.         {
  19.             this.pipeName = pipeName;
  20.             this.pipeServerStream = new NamedPipeServerStream(this.pipeName, PipeDirection.InOut,NUMOFTHREADS);
  21.         }
  22.         public void Send(string msg)
  23.         {
  24.             Task.Run(() =>
  25.             {
  26.                 if (!this.pipeServerStream.IsConnected)
  27.                 {
  28.                     return;
  29.                 }
  30.                 if (this.streamWriter == null)
  31.                 {
  32.                     this.streamWriter = new StreamWriter(pipeServerStream);
  33.                     this.streamWriter.AutoFlush = true;
  34.                 }
  35.                 this.streamWriter.WriteLine(msg);
  36.                 this.streamWriter.Flush();
  37.                 this.pipeServerStream.WaitForPipeDrain();
  38.             });
  39.         }
  40.         public void Receive()
  41.         {
  42.             Task.Run(() =>
  43.             {
  44.                 if (!this.pipeServerStream.IsConnected)
  45.                 {
  46.                     this.pipeServerStream.WaitForConnection();
  47.                 }
  48.                 if (this.streamReader == null)
  49.                 {
  50.                     this.streamReader = new StreamReader(pipeServerStream);
  51.                 }
  52.                 try
  53.                 {
  54.                     string? msg = streamReader.ReadLine();
  55.                     if (!string.IsNullOrEmpty(msg))
  56.                     {
  57.                         Received?.Invoke($"[]{msg}");
  58.                     }
  59.                 }
  60.                 catch (Exception ex)
  61.                 {
  62.                     Console.WriteLine(ex.Message);
  63.                     Console.WriteLine(ex.StackTrace);
  64.                 }
  65.                 finally
  66.                 {
  67.                     Task.Delay(500);
  68.                 }
  69.             });
  70.         }
  71.         public void Dispose()
  72.         {
  73.             if (pipeServerStream != null)
  74.             {
  75.                 pipeServerStream.Close();
  76.                 pipeServerStream.Dispose();
  77.             }
  78.         }
  79.     }
  80. }
复制代码
 
在上述示例中,有两个方法分别用于实现数据的发送(Send)和和接收(Receive)。接下来在FrmMain 页面中创建NamedPipeServer实例,以及分别用于实现接收和发送的事件,如下所示:
 
  1. using DemoPipe.Common;
  2. namespace DemoNamedPipeServer
  3. {
  4.     public partial class FrmMain : Form
  5.     {
  6.         private NamedPipeServer pipeServer;
  7.         public FrmMain()
  8.         {
  9.             InitializeComponent();
  10.             pipeServer = new NamedPipeServer("okcoder");
  11.             pipeServer.Received += new Action<string>((string msg) =>
  12.             {
  13.                 this.txtReceiveMsg.Invoke(() =>
  14.                 {
  15.                     this.txtReceiveMsg.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}:{msg}\r\n");
  16.                 });
  17.             });
  18.         }
  19.         private void btnSend_Click(object sender, EventArgs e)
  20.         {
  21.             try
  22.             {
  23.                 string msg = this.txtSendMsg.Text;
  24.                 if (!string.IsNullOrEmpty(msg))
  25.                 {
  26.                     pipeServer.Send(msg);
  27.                 }
  28.             }
  29.             catch (Exception ex)
  30.             {
  31.                 Console.WriteLine(ex.Message);
  32.                 Console.WriteLine(ex.StackTrace);
  33.             }
  34.         }
  35.         private void btnReceive_Click(object sender, EventArgs e)
  36.         {
  37.             this.pipeServer.Receive();
  38.         }
  39.     }
  40. }
复制代码
 
客户端

 
客户端采用WinForm可执行程序的方式实现【DemoNamedPipeClient】,主要实现数据的发送和接收,首选创建NamedPipeClient类,封装对NamedPipeClientStream的操作。在此实例中如果没有连接 ,则先进行连接 ,然后再进行数据交互,如下所示:
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO.Pipes;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace DemoPipe.Common
  9. {
  10.     public class NamedPipeClient:IDisposable
  11.     {
  12.         private readonly int NUMOFTHREADS = 4;
  13.         private string pipeName;
  14.         private NamedPipeClientStream pipeClientStream;
  15.         private StreamWriter streamWriter;
  16.         private CancellationTokenSource cts;
  17.         private CancellationToken token;
  18.         public Action<string> Received;
  19.         private StreamReader streamReader;
  20.         public NamedPipeClient(string pipeName)
  21.         {
  22.             this.pipeName = pipeName;
  23.             this.pipeClientStream = new NamedPipeClientStream(".", this.pipeName, PipeDirection.InOut);
  24.         }
  25.         public void Send(string msg)
  26.         {
  27.             Task.Run(() =>
  28.             {
  29.                 if (!this.pipeClientStream.IsConnected)
  30.                 {
  31.                     this.pipeClientStream.Connect(1000);
  32.                 }
  33.                 if (this.streamWriter == null)
  34.                 {
  35.                     this.streamWriter = new StreamWriter(pipeClientStream);
  36.                     this.streamWriter.AutoFlush = true;
  37.                 }
  38.                 this.streamWriter.WriteLine(msg);
  39.                 this.streamWriter.Flush();
  40.                 this.pipeClientStream.WaitForPipeDrain();
  41.             });
  42.         }
  43.         public void Receive()
  44.         {
  45.             Task.Run(() =>
  46.             {
  47.                 if (!this.pipeClientStream.IsConnected)
  48.                 {
  49.                     this.pipeClientStream.Connect(1000);
  50.                 }
  51.                 if (this.streamReader == null)
  52.                 {
  53.                     this.streamReader = new StreamReader(pipeClientStream);
  54.                 }
  55.                 try
  56.                 {
  57.                     string? msg = streamReader.ReadLine();
  58.                     if (!string.IsNullOrEmpty(msg))
  59.                     {
  60.                         Received?.Invoke($"[]{msg}");
  61.                     }
  62.                 }
  63.                 catch (Exception ex)
  64.                 {
  65.                     Console.WriteLine(ex.Message);
  66.                     Console.WriteLine(ex.StackTrace);
  67.                 }
  68.                 finally
  69.                 {
  70.                     Task.Delay(500);
  71.                 }
  72.             });
  73.         }
  74.         public void Dispose()
  75.         {
  76.             this.cts.Cancel();
  77.             if (pipeClientStream != null)
  78.             {
  79.                 pipeClientStream.Close();
  80.                 pipeClientStream.Dispose();
  81.             }
  82.         }
  83.     }
  84. }
复制代码
 
在上述实例中,接收和发送,都采用后台线程异步操作,避免线程阻塞造成UI主线程卡顿。接下来创建FrmMain中创建NamedPipeClient类的实例,以及UI上发送和接收的事件,如下所示:
 
  1. using DemoPipe.Common;
  2. namespace DemoNamedPipeClient
  3. {
  4.     public partial class FrmMain : Form
  5.     {
  6.         private NamedPipeClient pipeClient;
  7.         public FrmMain()
  8.         {
  9.             InitializeComponent();
  10.             this.pipeClient = new NamedPipeClient("okcoder");
  11.             pipeClient.Received += new Action<string>((string msg) =>
  12.             {
  13.                 this.txtReceiveMsg.Invoke(() =>
  14.                 {
  15.                     this.txtReceiveMsg.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}:{msg}\r\n");
  16.                 });
  17.             });
  18.         }
  19.         private void btnSend_Click(object sender, EventArgs e)
  20.         {
  21.             try
  22.             {
  23.                 string msg = this.txtSendMsg.Text;
  24.                 if (!string.IsNullOrEmpty(msg))
  25.                 {
  26.                     pipeClient.Send(msg);
  27.                 }
  28.             }
  29.             catch (Exception ex)
  30.             {
  31.                 Console.WriteLine(ex.Message);
  32.                 Console.WriteLine(ex.StackTrace);
  33.             }
  34.         }
  35.         private void btnReceive_Click(object sender, EventArgs e)
  36.         {
  37.             pipeClient.Receive();
  38.         }
  39.     }
  40. }
复制代码
 
在上述实例中,客户端和服务端采用同一个管道名称,这样才能进行通信。
 
实例演示

 
命名管道可以跨进程进行数据交互,并不局限于父子进程,可以同时启动,在Visual Studio中,可以在解决方案右键打开“配置启动项”对话框,如下所示:
 
4.png

 
运行实例效果如下所示:
 
5.gif

 
在本实例中,为了简化程序复杂度,分别手动点击进行发送和接收,实际工作中,可以采用事件同步机制实现数据的操作一致性。
 
以上就是《推荐一款基于.NET的进程间数据交互经典解决方案》的全部内容,旨在抛砖引玉,一起学习,共同进步。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册