1. 命名管道
服务器端示例代码
csharp
using System;
using System.IO.Pipes;
using System.Text;
public class NamedPipeServer
{
public static void Main()
{
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
Console.WriteLine("Waiting for client connection...");
pipeServer.WaitForConnection();
Console.WriteLine("Client connected.");
byte[] buffer = new byte[256];
int bytesRead = pipeServer.Read(buffer, 0, buffer.Length);
string messageFromClient = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + messageFromClient);
// Send response back to client
string response = "Hello from server";
pipeServer.Write(Encoding.UTF8.GetBytes(response), 0, response.Length);
pipeServer.Flush();
}
}
}
客户端示例代码
csharp
using System;
using System.IO.Pipes;
using System.Text;
public class NamedPipeClient
{
public static void Main()
{
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut, PipeOptions.Asynchronous))
{
Console.WriteLine("Connecting to server...");
pipeClient.Connect();
Console.WriteLine("Sending message to server...");
string messageToSend = "Hello from client";
pipeClient.Write(Encoding.UTF8.GetBytes(messageToSend), 0, messageToSend.Length);
pipeClient.Flush();
// Read response from server
byte[] buffer = new byte[256];
int bytesRead = pipeClient.Read(buffer, 0, buffer.Length);
string messageFromServer = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + messageFromServer);
}
}
}
2. 匿名管道
父进程示例代码
csharp
using System;
using System.IO.Pipes;
public class ParentProcess
{
public static void Main()
{
using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.Out))
{
using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(pipeServer.GetClientHandleAsString()))
{
Console.WriteLine("Writing to child...");
string message = "Hello from parent";
byte[] buffer = Encoding.UTF8.GetBytes(message);
pipeServer.Write(buffer, 0, buffer.Length);
pipeServer.Flush();
}
}
}
}
子进程示例代码
csharp
using System;
using System.IO.Pipes;
public class ChildProcess
{
public static void Main(string[] args)
{
using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, args[0]))
{
byte[] buffer = new byte[256];
int bytesRead = pipeClient.Read(buffer, 0, buffer.Length);
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: " + message);
}
}
}
3. 管道通信的注意事项
确保管道的权限和安全设置正确,以防止未授权访问。
对于命名管道,确保管道名称唯一,避免冲突。
在使用匿名管道时,通常需要父进程创建管道并启动子进程。
处理管道断开和异常情况,确保资源得到释放。
结论
往期精品推荐: