C# 多进程通信是指在一个应用程序中,多个进程之间需要共享数据或者协同工作。为了实现这种通信,我们可以使用以下几种方法:
System.IO.Pipes.AnonymousPipeServerStream
和 System.IO.Pipes.AnonymousPipeClientStream
类来创建。示例代码:
// 服务器端
using (var server = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
{
// 创建客户端
var client = new AnonymousPipeClientStream(PipeDirection.In, server.GetClientHandleAsString());
// 写入数据
using (var writer = new StreamWriter(server))
{
writer.WriteLine("Hello from server!");
}
}
// 客户端
using (var client = new AnonymousPipeClientStream(PipeDirection.In, "client_handle"))
{
// 读取数据
using (var reader = new StreamReader(client))
{
Console.WriteLine(reader.ReadLine());
}
}
System.IO.Pipes.NamedPipeServerStream
和 System.IO.Pipes.NamedPipeClientStream
类来创建。示例代码:
// 服务器端
using (var server = new NamedPipeServerStream("my_pipe", PipeDirection.InOut))
{
// 等待客户端连接
server.WaitForConnection();
// 读取数据
using (var reader = new StreamReader(server))
{
Console.WriteLine(reader.ReadLine());
}
// 写入数据
using (var writer = new StreamWriter(server))
{
writer.WriteLine("Hello from server!");
}
}
// 客户端
using (var client = new NamedPipeClientStream(".", "my_pipe", PipeDirection.InOut))
{
// 连接到服务器
client.Connect();
// 写入数据
using (var writer = new StreamWriter(client))
{
writer.WriteLine("Hello from client!");
}
// 读取数据
using (var reader = new StreamReader(client))
{
Console.WriteLine(reader.ReadLine());
}
}
System.IO.MemoryMappedFiles.MemoryMappedFile
类来创建。示例代码:
// 服务器端
using (var mmf = MemoryMappedFile.CreateNew("my_shared_memory", 1024))
{
// 写入数据
using (var accessor = mmf.CreateViewAccessor())
{
accessor.Write(0, "Hello from server!");
}
}
// 客户端
using (var mmf = MemoryMappedFile.OpenExisting("my_shared_memory"))
{
// 读取数据
using (var accessor = mmf.CreateViewAccessor())
{
string message;
accessor.Read(0, out message);
Console.WriteLine(message);
}
}
System.Messaging.MessageQueue
类来创建。示例代码:
// 服务器端
using (var queue = MessageQueue.Create(".\\private$\\my_queue"))
{
// 发送消息
queue.Send("Hello from server!");
}
// 客户端
using (var queue = new MessageQueue(".\\private$\\my_queue"))
{
// 接收消息
var message = queue.Receive();
Console.WriteLine(message.Body);
}
System.Net.Sockets.Socket
类来创建。示例代码:
// 服务器端
using (var listener = new TcpListener(IPAddress.Loopback, 8080))
{
listener.Start();
// 接受客户端连接
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadLine());
}
}
// 客户端
using (var client = new TcpClient())
{
// 连接到服务器
client.Connect(IPAddress.Loopback, 8080);
// 发送数据
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
{
writer.WriteLine("Hello from client!");
writer.Flush();
}
}
这些通信机制都有各自的优缺点,根据实际需求选择合适的通信方式。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。