在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。