在C#项目编写过程中,经常会遇到两个程序需要进行通信问题,如果两个程序在同一设备上运行,则可以选择命名隧道方式通信。
优点:
1.代码实现简单
2.通信可靠,不易出现两个程序失联
缺点:
1.通信过程需要自处理
2.多线程并发有数据丢失风险
具体实现demo如下
- 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();
}
}
}
- 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();
}
}
}
本次写的是连续通信,在实际项目中,可能需要按业务需求自行封装