C# System.IO.Pipes include NamedPipeline send and receive data asynchronously

Install-Package System.IO.Pipes
//Server
using System.IO.Pipes;
using System.IO;
using System.Text.Json;
using System.Data;

namespace ConsoleApp3
{
    internal class Program
    {
        static long id = 1;
        static List<BookCategory> categoryCollection= new List<BookCategory>(Enum.GetValues<BookCategory>());
        static int categoryLen = categoryCollection.Count;

        static (long,long) GetStartEnd(int cnt=100000)
        {
            long end = Interlocked.Add(ref id, cnt);
            long start = end - cnt;
            return (start, end);
        }


        static async Task Main(string[] args)
        {
            await PipeServerSendData();
            Console.ReadLine();
        }

        static List<Book> GenerateBksList(int cnt=100000)
        {
            List<Book> bksList = new List<Book>(cnt);
            var(start,end) = GetStartEnd(cnt);

            for(long i=start; i<end;i++)
            {
                bksList.Add(new Book()
                {
                    Id = i,
                    Name = $"Name_{i}",
                    Author = $"Author_{i}",
                    Comment = $"Comment_{i}",
                    Content = $"Content_{i}",
                    Category = categoryCollection[(int)i % categoryLen],
                    Summary=$"Summary_{i}",
                    Title=$"Title_{i}",
                    Topic=$"Topic_{i}",
                    CreateTime=$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}",
                    UpdateTime= $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}"
                });
            }

            return bksList;
        }

        static async Task PipeServerSendData()
        {
            string pipeName = "SendDataPipe";
            Console.WriteLine($"{DateTime.Now},waiting for connecting...");

            using var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut);
            await server.WaitForConnectionAsync();
            Console.WriteLine($"{DateTime.Now},the client has connected");

            using var reader = new StreamReader(server, leaveOpen: true);
            using var writer = new StreamWriter(server, leaveOpen: true){ AutoFlush = true };

            string msg = await reader.ReadLineAsync();
            Console.WriteLine($"{DateTime.Now},receive data from client:{msg}");

            int batch = 0;
            using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10)) ;
            while(await timer.WaitForNextTickAsync())
            {
                if (!server.IsConnected)
                {
                    Console.WriteLine("Pipe disconnected, exit send loop.");
                    break;
                }
                try
                {
                    Console.WriteLine($"\n{DateTime.Now},start generating data...");
                    var bksList = GenerateBksList();

                    string jsonStr = JsonSerializer.Serialize(bksList);
                    await writer.WriteLineAsync(jsonStr.Length.ToString());
                    await writer.WriteLineAsync(jsonStr);
                    Console.WriteLine($"{DateTime.Now},send batch:{++batch} complete");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{DateTime.Now},{ex?.Message}");
                    break;
                }
            }
             
        }


    }

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public BookCategory Category { get; set; }
        public string Author { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public string CreateTime { get; set; }
        public string UpdateTime { get; set; }

        public override string ToString()
        {
            return $"Id:{Id},Name:{Name},Category:{Enum.GetName(typeof(BookCategory), Category)},Author:{Author}," +
                $"Comment:{Comment},Content:{Content},Summary:{Summary},Title:{Title},Topic:{Topic},CreateTime:{CreateTime}," +
                $"UpdateTime:{UpdateTime}";
        }
    }

    public enum BookCategory
    {
        Science = 10,
        Technology = 20,
        Engineering = 30,
        Math = 40
    }
}

 

 

Client

using System.IO.Pipes;
using System.Text.Json;

namespace ConsoleApp4
{
    internal class Program
    { 
        static async Task Main(string[] args)
        {
            await NamedPipeDemo();
            Console.ReadLine();
        }

        private static async Task NamedPipeDemo()
        {
            string pipeName = "SendDataPipe";
            using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);
            await client.ConnectAsync();
            Console.WriteLine($"In client,{DateTime.Now},has connected with the server!");

            using var writer = new StreamWriter(client,leaveOpen:true) { AutoFlush = true };
            using var reader = new StreamReader(client,leaveOpen: true);

            await writer.WriteLineAsync("Hello from client");

            while(true)
            {
                try
                {
                    string? lenStr = await reader.ReadLineAsync();
                    if(string.IsNullOrWhiteSpace(lenStr))
                    {
                        Console.WriteLine("Server closed pipe");
                        break;
                    }

                    string jsonStr = await reader.ReadLineAsync();
                    if(string.IsNullOrWhiteSpace(jsonStr))
                    {
                        Console.WriteLine("Read json null");
                        break;
                    }

                    var bksList = JsonSerializer.Deserialize<List<Book>>(jsonStr);
                    if(bksList!=null && bksList.Any())
                    {
                        Console.WriteLine($"First:{bksList.FirstOrDefault().ToString()}\nLast:{bksList.LastOrDefault().ToString()}\n\n\n");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex?.Message);
                }
            }
            string? resp = await reader.ReadLineAsync();
            Console.WriteLine($"In client,{DateTime.Now},received response: {resp}");
        }
    }

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public BookCategory Category { get; set; }
        public string Author { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public string CreateTime { get; set; }
        public string UpdateTime { get; set; }

        public override string ToString()
        {
            return $"Id:{Id},Name:{Name},Category:{Enum.GetName(typeof(BookCategory), Category)},Author:{Author}," +
                $"Comment:{Comment},Content:{Content},Summary:{Summary},Title:{Title},Topic:{Topic},CreateTime:{CreateTime}," +
                $"UpdateTime:{UpdateTime}";
        }
    }

    public enum BookCategory
    {
        Science = 10,
        Technology = 20,
        Engineering = 30,
        Math = 40
    }
}

 

 

 

 

image

 

 

 

 

image

 

 

image

 

 

 

image

 

posted @ 2026-11-22 19:37  FredGrit  阅读(7)  评论(0)    收藏  举报