在C#中,处理Linux进程间通信(IPC)的方法与在Windows中有所不同
System.Net.Sockets.TcpClient
和System.Net.Sockets.NetworkStream
类来创建TCP套接字。对于UDP通信,可以使用System.Net.Sockets.UdpClient
类。using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class TcpClientExample
{
static async Task Main(string[] args)
{
using (TcpClient client = new TcpClient("localhost", 8080))
{
using (NetworkStream stream = client.GetStream())
{
string message = "Hello, Server!";
byte[] data = Encoding.ASCII.GetBytes(message);
await stream.WriteAsync(data, 0, data.Length);
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Server response: " + response);
}
}
}
}
System.IO.Pipes
类来创建和使用命名管道。using System;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;
class NamedPipeExample
{
static async Task Main(string[] args)
{
using (NamedPipeClientStream client = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut))
{
await client.ConnectAsync();
string message = "Hello, Server!";
byte[] data = Encoding.ASCII.GetBytes(message);
await client.WriteAsync(data, 0, data.Length);
byte[] buffer = new byte[1024];
int bytesRead = await client.ReadAsync(buffer, 0, buffer.Length);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Server response: " + response);
}
}
}
RabbitMQ.Client
库来与RabbitMQ进行交互。using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
class RabbitMQExample
{
static async Task Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
string message = "Hello, Server!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
Console.WriteLine(" [x] Sent '" + message + "'");
}
}
}
System.IO.MemoryMappedFiles
类来创建和使用共享内存。这些是在C#中进行Linux进程间通信的一些方法。你可以根据你的需求和场景选择合适的方法。