您好,登錄后才能下訂單哦!
在C#中,可以使用System.IO.Pipes
命名空間中的類來實現管道通信
服務器端代碼:
using System;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (var server = new NamedPipeServerStream("MyPipe"))
{
Console.WriteLine("Waiting for client connection...");
await server.WaitForConnectionAsync();
Console.WriteLine("Client connected.");
var buffer = new byte[1024];
var readBytes = await server.ReadAsync(buffer, 0, buffer.Length);
var message = Encoding.UTF8.GetString(buffer, 0, readBytes);
Console.WriteLine($"Received message: {message}");
var response = "Hello from server!";
var responseBuffer = Encoding.UTF8.GetBytes(response);
await server.WriteAsync(responseBuffer, 0, responseBuffer.Length);
Console.WriteLine("Sent response to client.");
}
}
}
客戶端代碼:
using System;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut))
{
Console.WriteLine("Connecting to server...");
await client.ConnectAsync();
Console.WriteLine("Connected to server.");
var message = "Hello from client!";
var messageBuffer = Encoding.UTF8.GetBytes(message);
await client.WriteAsync(messageBuffer, 0, messageBuffer.Length);
Console.WriteLine("Sent message to server.");
var buffer = new byte[1024];
var readBytes = await client.ReadAsync(buffer, 0, buffer.Length);
var response = Encoding.UTF8.GetString(buffer, 0, readBytes);
Console.WriteLine($"Received response: {response}");
}
}
}
這個示例中,服務器端和客戶端都使用了異步方法來讀取和寫入數據。首先,服務器端創建一個NamedPipeServerStream
實例并等待客戶端連接。客戶端使用NamedPipeClientStream
連接到服務器。然后,客戶端向服務器發送一條消息,服務器接收到消息后回復一條響應。客戶端接收到響應后輸出到控制臺。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。