当前位置:   article > 正文

C#跨进程通信全方位指南:深入实践命名管道、WCF与gRPC_wcf 与 grpc

wcf 与 grpc

一、命名管道(Named Pipes)

1. 服务器端

 

Csharp

  1. using System.IO.Pipes;
  2. using System.Threading.Tasks;
  3. public class NamedPipeServer
  4. {
  5. private NamedPipeServerStream _pipeServer;
  6. public async Task StartServer(string pipeName)
  7. {
  8. _pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
  9. await _pipeServer.WaitForConnectionAsync();
  10. Console.WriteLine("Client connected.");
  11. byte[] buffer = new byte[1024];
  12. int bytesRead;
  13. while ((bytesRead = await _pipeServer.ReadAsync(buffer, 0, buffer.Length)) != 0)
  14. {
  15. string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
  16. Console.WriteLine($"Received from client: {message}");
  17. // Respond to the client
  18. string response = $"Echo: {message}";
  19. byte[] responseBuffer = Encoding.UTF8.GetBytes(response);
  20. await _pipeServer.WriteAsync(responseBuffer, 0, responseBuffer.Length);
  21. }
  22. Console.WriteLine("Client disconnected.");
  23. }
  24. }

注释:创建NamedPipeServer类,使用NamedPipeServerStream创建命名管道服务器,等待客户端连接。当接收到客户端消息时,打印并回传消息。

2. 客户端

 

Csharp

  1. using System.IO.Pipes;
  2. using System.Threading.Tasks;
  3. public class NamedPipeClient
  4. {
  5. public async Task Send(string pipeName, string message)
  6. {
  7. using NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None);
  8. await pipeClient.ConnectAsync();
  9. Console.WriteLine("Connected to server.");
  10. byte[] messageBytes = Encoding.UTF8.GetBytes(message);
  11. await pipeClient.WriteAsync(messageBytes, 0, messageBytes.Length);
  12. Console.WriteLine("Message sent.");
  13. // Read server's response
  14. byte[] buffer = new byte[1024];
  15. int bytesRead = await pipeClient.ReadAsync(buffer, 0, buffer.Length);
  16. string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
  17. Console.WriteLine($"Received from server: {response}");
  18. }
  19. }

注释:创建NamedPipeClient类,使用NamedPipeClientStream创建命名管道客户端,连接到服务器并发送消息。随后读取并打印服务器的响应。

二、Windows Communication Foundation (WCF)

1. 服务端

 

Csharp

  1. using System.ServiceModel;
  2. [ServiceContract]
  3. public interface ICommunicationService
  4. {
  5. [OperationContract]
  6. string Echo(string message);
  7. }
  8. public class CommunicationService : ICommunicationService
  9. {
  10. public string Echo(string message)
  11. {
  12. return $"Echo: {message}";
  13. }
  14. }
  15. public class WcfServer
  16. {
  17. public void StartService(string baseAddress)
  18. {
  19. ServiceHost host = new ServiceHost(typeof(CommunicationService), new Uri(baseAddress));
  20. host.AddServiceEndpoint(typeof(ICommunicationService), new NetNamedPipeBinding(), "Pipe");
  21. host.Open();
  22. Console.WriteLine("WCF service started.");
  23. }
  24. }

注释:定义ICommunicationService接口和CommunicationService实现,使用WCF创建ServiceHost,绑定到命名管道并启动服务。

2. 客户端

 

Csharp

  1. using System.ServiceModel;
  2. public class WcfClient
  3. {
  4. public string CallService(string baseAddress, string message)
  5. {
  6. ChannelFactory<ICommunicationService> factory = new ChannelFactory<ICommunicationService>(new NetNamedPipeBinding(), new EndpointAddress(baseAddress + "/Pipe"));
  7. ICommunicationService serviceProxy = factory.CreateChannel();
  8. string response = serviceProxy.Echo(message);
  9. ((IClientChannel)serviceProxy).Close();
  10. factory.Close();
  11. return response;
  12. }
  13. }

注释:创建WcfClient类,使用ChannelFactory创建服务代理,调用Echo方法并返回响应。最后关闭通道和工厂。

三、gRPC

1. 定义服务(.proto文件)

 

Protobuf

  1. syntax = "proto3";
  2. package GrpcDemo;
  3. service CommunicationService {
  4. rpc Echo (EchoRequest) returns (EchoResponse);
  5. }
  6. message EchoRequest {
  7. string message = 1;
  8. }
  9. message EchoResponse {
  10. string response = 1;
  11. }

注释:定义gRPC服务接口CommunicationService,包含一个Echo方法,以及请求(EchoRequest)和响应(EchoResponse)消息类型。

2. 服务端

 

Csharp

  1. using Grpc.Core;
  2. using GrpcDemo;
  3. public class GrpcServer
  4. {
  5. public void StartServer(int port)
  6. {
  7. Server server = new Server
  8. {
  9. Services = { CommunicationService.BindService(new CommunicationServiceImpl()) },
  10. Ports = { new ServerPort("localhost", port, ServerCredentials.Insecure) }
  11. };
  12. server.Start();
  13. Console.WriteLine($"gRPC server started on port {port}.");
  14. }
  15. }
  16. public class CommunicationServiceImpl : CommunicationService.CommunicationServiceBase
  17. {
  18. public override Task<EchoResponse> Echo(EchoRequest request, ServerCallContext context)
  19. {
  20. return Task.FromResult(new EchoResponse { Response = $"Echo: {request.Message}" });
  21. }
  22. }

注释:创建GrpcServer类,使用gRPC库创建Server实例,绑定CommunicationServiceImplCommunicationService接口,并启动服务。

3. 客户端

 

Csharp

  1. using Grpc.Core;
  2. using GrpcDemo;
  3. public class GrpcClient
  4. {
  5. public async Task<string> CallService(string host, int port, string message)
  6. {
  7. Channel channel = new Channel(host, port, ChannelCredentials.Insecure);
  8. CommunicationService.CommunicationServiceClient client = new CommunicationService.CommunicationServiceClient(channel);
  9. EchoResponse response = await client.EchoAsync(new EchoRequest { Message = message });
  10. await channel.ShutdownAsync();
  11. return response.Response;
  12. }
  13. }

注释:创建GrpcClient类,使用gRPC库创建Channel和客户端代理,调用EchoAsync方法并返回响应。最后关闭通道。

四、总结

本文从零开始,详细介绍了如何在C#中使用命名管道、WCF与gRPC实现跨进程通信。对于每种技术,我们都提供了完整的服务器端和客户端代码示例,并配以详尽的注释,解释了代码的工作原理和使用场景。通过这些内容,您应已全面理解如何在C#中使用这三种技术进行跨进程通信,并掌握了它们各自的特点和适用场景。结合文中提供的代码示例与注释,您可以根据项目需求选择合适的技术进行跨进程通信,并为进一步提升跨进程通信的性能与安全性打下坚实基础。

五、进阶话题

  • 命名管道高级特性:如安全属性设置、异步读写、超时处理等。
  • WCF高级特性:如配置文件、安全性、事务支持、可靠会话等。
  • gRPC高级特性:如流式传输、双向流、错误处理、TLS加密等。
  • 跨进程通信性能对比:对比不同技术在吞吐量、延迟、资源消耗等方面的性能差异

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/847761
推荐阅读
相关标签
  

闽ICP备14008679号