您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。