您的位置:首页 > 房产 > 家装 > 【C# 】Pipe管道通信使用

【C# 】Pipe管道通信使用

2024/10/6 0:38:00 来源:https://blog.csdn.net/wangnaisheng/article/details/140541787  浏览:    关键词:【C# 】Pipe管道通信使用

管道通信

        管道通信(Pipe Communication)可以用来在两个或多个进程之间传递数据。

        管道可以是匿名的也可以是有名的,有名管道允许不同进程间的通信,而匿名管道通常用于父子进程之间的通信。

        详细参考pipe管道通信原理_核间通信pipe通信-CSDN博客

 

管道实例

服务器端会创建一个命名管道并等待客户端连接,

客户端则会尝试连接到这个管道,并发送一条消息给服务器端,服务器端接收到消息后会打印出来。

服务器端代码 (PipeServer)

服务器端的代码可以写成方法,或是集成到需要的地方使用。参考代码如下:

using System;
using System.IO.Pipes;
using System.Text;class PipeServer
{static void Main(string[] args){using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("MyPipeName", PipeDirection.InOut)){Console.WriteLine("Waiting for a client...");pipeServer.WaitForConnection(); // 等待客户端连接Console.WriteLine("Connected.");// 读取客户端发送的数据byte[] bytes = new byte[1024];int readBytes = pipeServer.Read(bytes, 0, bytes.Length);string data = Encoding.ASCII.GetString(bytes, 0, readBytes);Console.WriteLine($"Received: {data}");// 向客户端发送响应string response = "Hello back from the server!";byte[] responseBytes = Encoding.ASCII.GetBytes(response);pipeServer.Write(responseBytes, 0, responseBytes.Length);pipeServer.Flush();pipeServer.Disconnect(); // 断开连接}}
}

客户端代码 (PipeClient)

客户端的代码可以写成方法,或是集成到需要的地方使用。参考代码如下: 

using System;
using System.IO.Pipes;
using System.Text;class PipeClient
{static void Main(string[] args){using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "MyPipeName", PipeDirection.InOut)){pipeClient.Connect(1000); // 尝试连接,超时时间为1秒Console.WriteLine("Connected to server.");// 向服务器发送数据string message = "Hello from the client!";byte[] bytes = Encoding.ASCII.GetBytes(message);pipeClient.Write(bytes, 0, bytes.Length);pipeClient.Flush();// 读取服务器响应byte[] responseBytes = new byte[1024];int bytesRead = pipeClient.Read(responseBytes, 0, responseBytes.Length);string response = Encoding.ASCII.GetString(responseBytes, 0, bytesRead);Console.WriteLine($"Received from server: {response}");pipeClient.Close(); // 关闭管道}}
}

 在这个例子中,服务器和客户端都使用相同的管道名字 "MyPipeName" 进行通信。服务器首先创建管道并等待客户端连接,而客户端则尝试连接到服务器端创建的管道,并发送一个字符串消息。服务器和客户端都实现了读写操作,使得数据可以在两者之间双向流动。当客户端向服务器发送消息后,服务器会接收到消息并回发一条响应给客户端。同样地,客户端在发送消息后也会读取来自服务器的响应。

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com