赞
踩
一、命名管道(Named Pipes)
1. 服务器端
- using System.IO.Pipes;
- using System.Threading.Tasks;
-
- public class NamedPipeServer
- {
- private NamedPipeServerStream _pipeServer;
-
- public async Task StartServer(string pipeName)
- {
- _pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
-
- await _pipeServer.WaitForConnectionAsync();
-
- Console.WriteLine("Client connected.");
-
- byte[] buffer = new byte[1024];
- int bytesRead;
-
- while ((bytesRead = await _pipeServer.ReadAsync(buffer, 0, buffer.Length)) != 0)
- {
- string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
- Console.WriteLine($"Received from client: {message}");
-
- // Respond to the client
- string response = $"Echo: {message}";
- byte[] responseBuffer = Encoding.UTF8.GetBytes(response);
- await _pipeServer.WriteAsync(responseBuffer, 0, responseBuffer.Length);
- }
-
- Console.WriteLine("Client disconnected.");
- }
- }
注释:创建NamedPipeServer
类,使用NamedPipeServerStream
创建命名管道服务器,等待客户端连接。当接收到客户端消息时,打印并回传消息。
2. 客户端
Csharp
- using System.IO.Pipes;
- using System.Threading.Tasks;
-
- public class NamedPipeClient
- {
- public async Task Send(string pipeName, string message)
- {
- using NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None);
-
- await pipeClient.ConnectAsync();
-
- Console.WriteLine("Connected to server.");
-
- byte[] messageBytes = Encoding.UTF8.GetBytes(message);
- await pipeClient.WriteAsync(messageBytes, 0, messageBytes.Length);
-
- Console.WriteLine("Message sent.");
-
- // Read server's response
- byte[] buffer = new byte[1024];
- int bytesRead = await pipeClient.ReadAsync(buffer, 0, buffer.Length);
- string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
- Console.WriteLine($"Received from server: {response}");
- }
- }
注释:创建NamedPipeClient
类,使用NamedPipeClientStream
创建命名管道客户端,连接到服务器并发送消息。随后读取并打印服务器的响应。
二、Windows Communication Foundation (WCF)
1. 服务端
Csharp
- using System.ServiceModel;
-
- [ServiceContract]
- public interface ICommunicationService
- {
- [OperationContract]
- string Echo(string message);
- }
-
- public class CommunicationService : ICommunicationService
- {
- public string Echo(string message)
- {
- return $"Echo: {message}";
- }
- }
-
- public class WcfServer
- {
- public void StartService(string baseAddress)
- {
- ServiceHost host = new ServiceHost(typeof(CommunicationService), new Uri(baseAddress));
- host.AddServiceEndpoint(typeof(ICommunicationService), new NetNamedPipeBinding(), "Pipe");
- host.Open();
-
- Console.WriteLine("WCF service started.");
- }
- }
注释:定义ICommunicationService
接口和CommunicationService
实现,使用WCF创建ServiceHost
,绑定到命名管道并启动服务。
2. 客户端
Csharp
- using System.ServiceModel;
-
- public class WcfClient
- {
- public string CallService(string baseAddress, string message)
- {
- ChannelFactory<ICommunicationService> factory = new ChannelFactory<ICommunicationService>(new NetNamedPipeBinding(), new EndpointAddress(baseAddress + "/Pipe"));
- ICommunicationService serviceProxy = factory.CreateChannel();
-
- string response = serviceProxy.Echo(message);
-
- ((IClientChannel)serviceProxy).Close();
- factory.Close();
-
- return response;
- }
- }
注释:创建WcfClient
类,使用ChannelFactory
创建服务代理,调用Echo
方法并返回响应。最后关闭通道和工厂。
三、gRPC
1. 定义服务(.proto文件)
Protobuf
- syntax = "proto3";
-
- package GrpcDemo;
-
- service CommunicationService {
- rpc Echo (EchoRequest) returns (EchoResponse);
- }
-
- message EchoRequest {
- string message = 1;
- }
-
- message EchoResponse {
- string response = 1;
- }
注释:定义gRPC服务接口CommunicationService
,包含一个Echo
方法,以及请求(EchoRequest
)和响应(EchoResponse
)消息类型。
2. 服务端
Csharp
- using Grpc.Core;
- using GrpcDemo;
-
- public class GrpcServer
- {
- public void StartServer(int port)
- {
- Server server = new Server
- {
- Services = { CommunicationService.BindService(new CommunicationServiceImpl()) },
- Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
- };
-
- server.Start();
-
- Console.WriteLine($"gRPC server started on port {port}.");
- }
- }
-
- public class CommunicationServiceImpl : CommunicationService.CommunicationServiceBase
- {
- public override Task<EchoResponse> Echo(EchoRequest request, ServerCallContext context)
- {
- return Task.FromResult(new EchoResponse { Response = $"Echo: {request.Message}" });
- }
- }
注释:创建GrpcServer
类,使用gRPC库创建Server
实例,绑定CommunicationServiceImpl
到CommunicationService
接口,并启动服务。
3. 客户端
Csharp
- using Grpc.Core;
- using GrpcDemo;
-
- public class GrpcClient
- {
- public async Task<string> CallService(string host, int port, string message)
- {
- Channel channel = new Channel(host, port, ChannelCredentials.Insecure);
- CommunicationService.CommunicationServiceClient client = new CommunicationService.CommunicationServiceClient(channel);
-
- EchoResponse response = await client.EchoAsync(new EchoRequest { Message = message });
-
- await channel.ShutdownAsync();
-
- return response.Response;
- }
- }
注释:创建GrpcClient
类,使用gRPC库创建Channel
和客户端代理,调用EchoAsync
方法并返回响应。最后关闭通道。
四、总结
本文从零开始,详细介绍了如何在C#中使用命名管道、WCF与gRPC实现跨进程通信。对于每种技术,我们都提供了完整的服务器端和客户端代码示例,并配以详尽的注释,解释了代码的工作原理和使用场景。通过这些内容,您应已全面理解如何在C#中使用这三种技术进行跨进程通信,并掌握了它们各自的特点和适用场景。结合文中提供的代码示例与注释,您可以根据项目需求选择合适的技术进行跨进程通信,并为进一步提升跨进程通信的性能与安全性打下坚实基础。
五、进阶话题
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。