C# 实现一个封装好的管道通讯实例
时间: 2023-10-19 08:22:01 浏览: 47
下面是一个简单的 C# 封装好的管道通讯实例:
```csharp
using System;
using System.IO.Pipes;
using System.Text;
namespace PipeCommunication
{
public class PipeClient
{
private NamedPipeClientStream pipeClient;
public PipeClient(string pipeName)
{
pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);
}
public void Connect()
{
pipeClient.Connect();
}
public void Write(string message)
{
byte[] buffer = Encoding.UTF8.GetBytes(message);
pipeClient.Write(buffer, 0, buffer.Length);
pipeClient.Flush();
}
public string Read()
{
byte[] buffer = new byte[pipeClient.InBufferSize];
pipeClient.Read(buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer).TrimEnd('\0');
}
public void Close()
{
pipeClient.Close();
}
}
public class PipeServer
{
private NamedPipeServerStream pipeServer;
public PipeServer(string pipeName)
{
pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte);
}
public void Start()
{
pipeServer.WaitForConnection();
}
public void Write(string message)
{
byte[] buffer = Encoding.UTF8.GetBytes(message);
pipeServer.Write(buffer, 0, buffer.Length);
pipeServer.Flush();
}
public string Read()
{
byte[] buffer = new byte[pipeServer.InBufferSize];
pipeServer.Read(buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer).TrimEnd('\0');
}
public void Close()
{
pipeServer.Close();
}
}
}
```
使用该类进行管道通讯的示例如下:
```csharp
using System;
namespace PipeCommunication
{
class Program
{
static void Main(string[] args)
{
// 创建管道服务器
PipeServer server = new PipeServer("mypipe");
// 启动服务器
server.Start();
// 读取客户端发送的消息
string message = server.Read();
Console.WriteLine("客户端发送的消息:{0}", message);
// 向客户端发送消息
server.Write("你好,客户端!");
// 关闭服务器
server.Close();
Console.ReadKey();
}
}
}
```
客户端代码示例:
```csharp
using System;
namespace PipeCommunication
{
class Program
{
static void Main(string[] args)
{
// 创建管道客户端
PipeClient client = new PipeClient("mypipe");
// 连接服务器
client.Connect();
// 向服务器发送消息
client.Write("你好,服务器!");
// 读取服务器发送的消息
string message = client.Read();
Console.WriteLine("服务器发送的消息:{0}", message);
// 关闭客户端
client.Close();
Console.ReadKey();
}
}
}
```
这个示例是一个简单的管道通讯实现,你可以根据实际需求进行修改和扩展。