• 【微软技术栈】C#.NET 中的管道操作


    C#.NET 管道为进程间通信提供了平台。 管道分为两种类型:

    • 匿名管道

      匿名管道在本地计算机上提供进程间通信。 与命名管道相比,虽然匿名管道需要的开销更少,但提供的服务有限。 匿名管道是单向的,不能通过网络使用。 仅支持一个服务器实例。 匿名管道可用于线程间通信,也可用于父进程和子进程之间的通信,因为管道句柄可以轻松传递给所创建的子进程。在 .NET 中,可通过使用 AnonymousPipeServerStream 和 AnonymousPipeClientStream 类来实现匿名管道。

    • 命名管道。

      命名管道在管道服务器和一个或多个管道客户端之间提供进程间通信。 命名管道可以是单向的,也可以是双向的。 它们支持基于消息的通信,并允许多个客户端使用相同的管道名称同时连接到服务器进程。 命名管道还支持模拟,这样连接进程就可以在远程服务器上使用自己的权限。在 .NET 中,可通过使用 NamedPipeServerStream 和 NamedPipeClientStream 类来实现命名管道。

    1、如何:使用匿名管道进行本地进程间通信

    匿名管道在本地计算机上提供进程间通信。 它们提供的功能比命名管道少,但所需要的系统开销也少。 使用匿名管道,可以在本地计算机上更轻松地进行进程间通信。 不能使用匿名管道进行网络通信。

    若要实现匿名管道,请使用 AnonymousPipeServerStream 和 AnonymousPipeClientStream 类。

    1.1 示例 1

    下面的示例展示了如何使用匿名管道将字符串从父进程发送到子进程。 本示例在父进程中创建一个 AnonymousPipeServerStream 对象,其 PipeDirection 值为 Out。然后,父进程通过使用客户端句柄创建 AnonymousPipeClientStream 对象来创建子进程。 子进程的 PipeDirection 值为 In

    接下来,父进程将用户提供的字符串发送给子进程。 字符串在子进程的控制台中显示。

    下面的示例展示了服务器进程。

    1. using System;
    2. using System.IO;
    3. using System.IO.Pipes;
    4. using System.Diagnostics;
    5. class PipeServer
    6. {
    7. static void Main()
    8. {
    9. Process pipeClient = new Process();
    10. pipeClient.StartInfo.FileName = "pipeClient.exe";
    11. using (AnonymousPipeServerStream pipeServer =
    12. new AnonymousPipeServerStream(PipeDirection.Out,
    13. HandleInheritability.Inheritable))
    14. {
    15. Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
    16. pipeServer.TransmissionMode);
    17. // Pass the client process a handle to the server.
    18. pipeClient.StartInfo.Arguments =
    19. pipeServer.GetClientHandleAsString();
    20. pipeClient.StartInfo.UseShellExecute = false;
    21. pipeClient.Start();
    22. pipeServer.DisposeLocalCopyOfClientHandle();
    23. try
    24. {
    25. // Read user input and send that to the client process.
    26. using (StreamWriter sw = new StreamWriter(pipeServer))
    27. {
    28. sw.AutoFlush = true;
    29. // Send a 'sync message' and wait for client to receive it.
    30. sw.WriteLine("SYNC");
    31. pipeServer.WaitForPipeDrain();
    32. // Send the console input to the client process.
    33. Console.Write("[SERVER] Enter text: ");
    34. sw.WriteLine(Console.ReadLine());
    35. }
    36. }
    37. // Catch the IOException that is raised if the pipe is broken
    38. // or disconnected.
    39. catch (IOException e)
    40. {
    41. Console.WriteLine("[SERVER] Error: {0}", e.Message);
    42. }
    43. }
    44. pipeClient.WaitForExit();
    45. pipeClient.Close();
    46. Console.WriteLine("[SERVER] Client quit. Server terminating.");
    47. }
    48. }

    1.2 示例 2

    下面的示例展示了客户端进程。 服务器进程启动客户端进程,并为此进程提供客户端句柄。 客户端代码生成的可执行文件应命名为 pipeClient.exe,并在运行服务器进程前复制到服务器可执行文件所在的相同目录中。

    1. using System;
    2. using System.IO;
    3. using System.IO.Pipes;
    4. class PipeClient
    5. {
    6. static void Main(string[] args)
    7. {
    8. if (args.Length > 0)
    9. {
    10. using (PipeStream pipeClient =
    11. new AnonymousPipeClientStream(PipeDirection.In, args[0]))
    12. {
    13. Console.WriteLine("[CLIENT] Current TransmissionMode: {0}.",
    14. pipeClient.TransmissionMode);
    15. using (StreamReader sr = new StreamReader(pipeClient))
    16. {
    17. // Display the read text to the console
    18. string temp;
    19. // Wait for 'sync message' from the server.
    20. do
    21. {
    22. Console.WriteLine("[CLIENT] Wait for sync...");
    23. temp = sr.ReadLine();
    24. }
    25. while (!temp.StartsWith("SYNC"));
    26. // Read the server data and echo to the console.
    27. while ((temp = sr.ReadLine()) != null)
    28. {
    29. Console.WriteLine("[CLIENT] Echo: " + temp);
    30. }
    31. }
    32. }
    33. }
    34. Console.Write("[CLIENT] Press Enter to continue...");
    35. Console.ReadLine();
    36. }
    37. }

    2、如何:使用命名管道进行网络进程间通信

    命名管道在管道服务器和一个或多个管道客户端之间提供进程间通信。 它们比匿名管道(用于在本地计算机上提供进程间的通信)提供更多的功能。 命名管道支持跨网络和多个服务器实例的全双工通信、基于消息的通信以及客户端模拟,这样连接进程便可在远程服务器上使用自己的权限集。若要实现名称管道,请使用 NamedPipeServerStream 和 NamedPipeClientStream 类。

    2.1 示例 1

    下面的示例展示了如何使用 NamedPipeServerStream 类创建命名管道。 在此示例中,服务器进程创建四个线程。 每个线程都可以接受客户端连接。 然后,连接的客户端进程向服务器提供文件名。 如果客户端拥有足够的权限,服务器进程就会打开文件,并将它的内容发送回客户端。

    1. using System;
    2. using System.IO;
    3. using System.IO.Pipes;
    4. using System.Text;
    5. using System.Threading;
    6. public class PipeServer
    7. {
    8. private static int numThreads = 4;
    9. public static void Main()
    10. {
    11. int i;
    12. Thread?[] servers = new Thread[numThreads];
    13. Console.WriteLine("\n*** Named pipe server stream with impersonation example ***\n");
    14. Console.WriteLine("Waiting for client connect...\n");
    15. for (i = 0; i < numThreads; i++)
    16. {
    17. servers[i] = new Thread(ServerThread);
    18. servers[i]?.Start();
    19. }
    20. Thread.Sleep(250);
    21. while (i > 0)
    22. {
    23. for (int j = 0; j < numThreads; j++)
    24. {
    25. if (servers[j] != null)
    26. {
    27. if (servers[j]!.Join(250))
    28. {
    29. Console.WriteLine("Server thread[{0}] finished.", servers[j]!.ManagedThreadId);
    30. servers[j] = null;
    31. i--; // decrement the thread watch count
    32. }
    33. }
    34. }
    35. }
    36. Console.WriteLine("\nServer threads exhausted, exiting.");
    37. }
    38. private static void ServerThread(object? data)
    39. {
    40. NamedPipeServerStream pipeServer =
    41. new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);
    42. int threadId = Thread.CurrentThread.ManagedThreadId;
    43. // Wait for a client to connect
    44. pipeServer.WaitForConnection();
    45. Console.WriteLine("Client connected on thread[{0}].", threadId);
    46. try
    47. {
    48. // Read the request from the client. Once the client has
    49. // written to the pipe its security token will be available.
    50. StreamString ss = new StreamString(pipeServer);
    51. // Verify our identity to the connected client using a
    52. // string that the client anticipates.
    53. ss.WriteString("I am the one true server!");
    54. string filename = ss.ReadString();
    55. // Read in the contents of the file while impersonating the client.
    56. ReadFileToStream fileReader = new ReadFileToStream(ss, filename);
    57. // Display the name of the user we are impersonating.
    58. Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.",
    59. filename, threadId, pipeServer.GetImpersonationUserName());
    60. pipeServer.RunAsClient(fileReader.Start);
    61. }
    62. // Catch the IOException that is raised if the pipe is broken
    63. // or disconnected.
    64. catch (IOException e)
    65. {
    66. Console.WriteLine("ERROR: {0}", e.Message);
    67. }
    68. pipeServer.Close();
    69. }
    70. }
    71. // Defines the data protocol for reading and writing strings on our stream
    72. public class StreamString
    73. {
    74. private Stream ioStream;
    75. private UnicodeEncoding streamEncoding;
    76. public StreamString(Stream ioStream)
    77. {
    78. this.ioStream = ioStream;
    79. streamEncoding = new UnicodeEncoding();
    80. }
    81. public string ReadString()
    82. {
    83. int len = 0;
    84. len = ioStream.ReadByte() * 256;
    85. len += ioStream.ReadByte();
    86. byte[] inBuffer = new byte[len];
    87. ioStream.Read(inBuffer, 0, len);
    88. return streamEncoding.GetString(inBuffer);
    89. }
    90. public int WriteString(string outString)
    91. {
    92. byte[] outBuffer = streamEncoding.GetBytes(outString);
    93. int len = outBuffer.Length;
    94. if (len > UInt16.MaxValue)
    95. {
    96. len = (int)UInt16.MaxValue;
    97. }
    98. ioStream.WriteByte((byte)(len / 256));
    99. ioStream.WriteByte((byte)(len & 255));
    100. ioStream.Write(outBuffer, 0, len);
    101. ioStream.Flush();
    102. return outBuffer.Length + 2;
    103. }
    104. }
    105. // Contains the method executed in the context of the impersonated user
    106. public class ReadFileToStream
    107. {
    108. private string fn;
    109. private StreamString ss;
    110. public ReadFileToStream(StreamString str, string filename)
    111. {
    112. fn = filename;
    113. ss = str;
    114. }
    115. public void Start()
    116. {
    117. string contents = File.ReadAllText(fn);
    118. ss.WriteString(contents);
    119. }
    120. }

    2.2 示例 2

    下面的示例展示了使用 NamedPipeClientStream 类的客户端进程。 客户端连接到服务器进程,并将文件名发送到服务器。 因为此示例使用模拟,所以运行客户端应用的标识必须有权访问文件。 然后,服务器将文件内容发送回客户端。 接下来,文件内容在控制台中显示。

    1. using System;
    2. using System.Diagnostics;
    3. using System.IO;
    4. using System.IO.Pipes;
    5. using System.Security.Principal;
    6. using System.Text;
    7. using System.Threading;
    8. public class PipeClient
    9. {
    10. private static int numClients = 4;
    11. public static void Main(string[] args)
    12. {
    13. if (args.Length > 0)
    14. {
    15. if (args[0] == "spawnclient")
    16. {
    17. var pipeClient =
    18. new NamedPipeClientStream(".", "testpipe",
    19. PipeDirection.InOut, PipeOptions.None,
    20. TokenImpersonationLevel.Impersonation);
    21. Console.WriteLine("Connecting to server...\n");
    22. pipeClient.Connect();
    23. var ss = new StreamString(pipeClient);
    24. // Validate the server's signature string.
    25. if (ss.ReadString() == "I am the one true server!")
    26. {
    27. // The client security token is sent with the first write.
    28. // Send the name of the file whose contents are returned
    29. // by the server.
    30. ss.WriteString("c:\\textfile.txt");
    31. // Print the file to the screen.
    32. Console.Write(ss.ReadString());
    33. }
    34. else
    35. {
    36. Console.WriteLine("Server could not be verified.");
    37. }
    38. pipeClient.Close();
    39. // Give the client process some time to display results before exiting.
    40. Thread.Sleep(4000);
    41. }
    42. }
    43. else
    44. {
    45. Console.WriteLine("\n*** Named pipe client stream with impersonation example ***\n");
    46. StartClients();
    47. }
    48. }
    49. // Helper function to create pipe client processes
    50. private static void StartClients()
    51. {
    52. string currentProcessName = Environment.CommandLine;
    53. // Remove extra characters when launched from Visual Studio
    54. currentProcessName = currentProcessName.Trim('"', ' ');
    55. currentProcessName = Path.ChangeExtension(currentProcessName, ".exe");
    56. Process?[] plist = new Process?[numClients];
    57. Console.WriteLine("Spawning client processes...\n");
    58. if (currentProcessName.Contains(Environment.CurrentDirectory))
    59. {
    60. currentProcessName = currentProcessName.Replace(Environment.CurrentDirectory, String.Empty);
    61. }
    62. // Remove extra characters when launched from Visual Studio
    63. currentProcessName = currentProcessName.Replace("\\", String.Empty);
    64. currentProcessName = currentProcessName.Replace("\"", String.Empty);
    65. int i;
    66. for (i = 0; i < numClients; i++)
    67. {
    68. // Start 'this' program but spawn a named pipe client.
    69. plist[i] = Process.Start(currentProcessName, "spawnclient");
    70. }
    71. while (i > 0)
    72. {
    73. for (int j = 0; j < numClients; j++)
    74. {
    75. if (plist[j] != null)
    76. {
    77. if (plist[j]!.HasExited)
    78. {
    79. Console.WriteLine($"Client process[{plist[j]?.Id}] has exited.");
    80. plist[j] = null;
    81. i--; // decrement the process watch count
    82. }
    83. else
    84. {
    85. Thread.Sleep(250);
    86. }
    87. }
    88. }
    89. }
    90. Console.WriteLine("\nClient processes finished, exiting.");
    91. }
    92. }
    93. // Defines the data protocol for reading and writing strings on our stream.
    94. public class StreamString
    95. {
    96. private Stream ioStream;
    97. private UnicodeEncoding streamEncoding;
    98. public StreamString(Stream ioStream)
    99. {
    100. this.ioStream = ioStream;
    101. streamEncoding = new UnicodeEncoding();
    102. }
    103. public string ReadString()
    104. {
    105. int len;
    106. len = ioStream.ReadByte() * 256;
    107. len += ioStream.ReadByte();
    108. var inBuffer = new byte[len];
    109. ioStream.Read(inBuffer, 0, len);
    110. return streamEncoding.GetString(inBuffer);
    111. }
    112. public int WriteString(string outString)
    113. {
    114. byte[] outBuffer = streamEncoding.GetBytes(outString);
    115. int len = outBuffer.Length;
    116. if (len > UInt16.MaxValue)
    117. {
    118. len = (int)UInt16.MaxValue;
    119. }
    120. ioStream.WriteByte((byte)(len / 256));
    121. ioStream.WriteByte((byte)(len & 255));
    122. ioStream.Write(outBuffer, 0, len);
    123. ioStream.Flush();
    124. return outBuffer.Length + 2;
    125. }
    126. }

    2.3 可靠编程

    因为此示例中的客户端进程和服务器进程可以在同一台计算机上运行,所以提供给 NamedPipeClientStream 对象的服务器名称为 "."。 如果客户端进程和服务器进程在不同的计算机上运行,"." 会被替换为运行服务器进程的计算机的网络名称。

  • 相关阅读:
    springboot+校园交友平台小程序 毕业设计-附源码191733
    Grafana+Prometheus打造运维监控系统(一)-安装篇
    Java 19新特性:Structured Concurrency (结构化并发编程)
    trino on yarn
    牛客刷题<17>用3-8译码器实现全减器
    pdf文档内容提取pdfplumber、PyPDF2
    【数据结构与算法】五、树结构-从二叉树到B+Tree
    Python——使用asyncio包处理并发
    蓝桥杯 第 1 场算法双周赛 第三题 分组【算法赛】c++ 贪心+双指针
    hbuilder x配置 配置使用 vue-cli和微信开发者工具
  • 原文地址:https://blog.csdn.net/m0_51887793/article/details/134387818