C# WebSocket console as service provide data, another console as client,send request periodically

//Server:
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;

namespace ConsoleApp7
{
    public class Program
    {
        static async Task Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            var listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:5000/ws/");
            listener.Start();

            Console.WriteLine($"{DateTime.Now},WebSocket Server started at ws://localhost:5000/ws/");
            while (true)
            {
                var context = await listener.GetContextAsync();

                if (context.Request.IsWebSocketRequest)
                {
                    _ = HandleClient(context);
                }
                else
                {
                    context.Response.StatusCode = 400;
                    context.Response.Close();
                }
            }
        } 

        static async Task HandleClient(HttpListenerContext context)
        {
            var wsContext = await context.AcceptWebSocketAsync(null);
            var socket = wsContext.WebSocket;

            Console.WriteLine($"{DateTime.Now},Client connected");

            var buffer = new byte[1024];

            while (socket.State == WebSocketState.Open)
            {
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                    break;
                }

                var request = Encoding.UTF8.GetString(buffer, 0, result.Count);
                //Console.WriteLine($"Received: {request}");

                var bksList = GetBooksList();

                var json = JsonSerializer.Serialize(bksList);
                var bytes = Encoding.UTF8.GetBytes(json);

                await socket.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None);

                var ids = bksList.Select(x => x.Id);
                string msg = $"MinId:{ids.Min()},MaxId:{ids.Max()}";
                Console.WriteLine($"{DateTime.Now.ToString("yyyyMMddHHmmssffff")} sent data,{msg}");
            }
        }

        static int idx = 0;
        static int GetIdx()
        {
            return Interlocked.Increment(ref idx);
        }

        static List<Book> GetBooksList()
        {
            List<Book> bksList = new List<Book>();
            for(int i=0;i<10000;i++)
            {
                var a = GetIdx();
                bksList.Add(new Book()
                {
                    Id =a,
                    Name=$"Name_{a}",
                    Author=$"Author_{a}",
                    ISBN=$"ISBN_{a}_{Guid.NewGuid():N}",
                    Comment=$"Comment_{a}",
                    Content=$"Content_{a}",
                    Summary=$"Summary_{a}",
                    Title=$"Title_{a}",
                    Topic=$"Topic_{a}"
                 });
            }
            return bksList;
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ISBN { 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;  }
    }
}



#Client
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;


namespace ConsoleApp8
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await WebSocketReceiveDemo();
        }

        static async Task WebSocketReceiveDemo()
        {
            var ws = new ClientWebSocket();
            await ws.ConnectAsync(new Uri("ws://localhost:5000/ws/"), CancellationToken.None);

            Console.WriteLine("Connected to server");

            var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(10));

            while (await timer.WaitForNextTickAsync())
            {
                if (ws.State != WebSocketState.Open)
                {
                    break;
                }
                
                var msg = Encoding.UTF8.GetBytes("get_data");
                await ws.SendAsync(msg, WebSocketMessageType.Text, true, CancellationToken.None);

                Console.WriteLine($"{DateTime.Now.ToString("yyyyMMddHHmmssffff")},Request sent");
                //var buffer = new byte[1024 * 1024 * 1024];
                //var result = await ws.ReceiveAsync(buffer, CancellationToken.None);
                var buffer = new byte[4096];
                var ms = new MemoryStream();

                WebSocketReceiveResult result;
                do
                {
                    result = await ws.ReceiveAsync(buffer, CancellationToken.None);
                    ms.Write(buffer, 0, result.Count);
                } while (!result.EndOfMessage);

                var jsonStr = Encoding.UTF8.GetString(ms.ToArray());
                List<Book> booksList = JsonSerializer.Deserialize<List<Book>>(jsonStr) ?? new List<Book>();
                Console.WriteLine($"{DateTime.Now.ToString("yyyyMMddHHmmssffff")},received {booksList.Count} data," +
                    $"stream length:{ms.Length},json length:{jsonStr.Length}");
                if (booksList.Any())
                {
                    int bksCnt = booksList.Count();
                    Console.WriteLine($"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}\nFirst:{booksList[0]}\nLast:{booksList[bksCnt-1]}\n");
                }
                timer.Period = TimeSpan.FromSeconds(5);
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ISBN { 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 override string ToString()
        {
            return $"Id:{Id},Name:{Name},ISBN:{ISBN},Author:{Author},Comment:{Comment}" +
                $",Content:{Content},Summary:{Summary},Title:{Title},Topic:{Topic}";
        }
    }
}

 

 

2026-03-18 23:02:20,WebSocket Server started at ws://localhost:5000/ws/
2026-03-18 23:02:22,Client connected
202603182302229612 sent data,MinId:1,MaxId:10000
202603182302231173 sent data,MinId:10001,MaxId:20000
202603182302282621 sent data,MinId:20001,MaxId:30000
202603182302333911 sent data,MinId:30001,MaxId:40000
202603182302384676 sent data,MinId:40001,MaxId:50000
202603182302435643 sent data,MinId:50001,MaxId:60000
202603182302486174 sent data,MinId:60001,MaxId:70000
202603182302536839 sent data,MinId:70001,MaxId:80000
202603182302587977 sent data,MinId:80001,MaxId:90000
202603182303038893 sent data,MinId:90001,MaxId:100000
202603182303089561 sent data,MinId:100001,MaxId:110000

image

 

 

 

 

Connected to server
202603182302228557,Request sent
202603182302230731,received 10000 data,stream length:2220047,json length:2220047
202603182302230734
First:Id:1,Name:Name_1,ISBN:ISBN_1_aed865cadf7a4c34bfc98bf685ec7c5a,Author:Author_1,Comment:Comment_1,Content:Content_1,Summary:Summary_1,Title:Title_1,Topic:Topic_1
Last:Id:10000,Name:Name_10000,ISBN:ISBN_10000_9ec64474360641b79306ac996e11e57e,Author:Author_10000,Comment:Comment_10000,Content:Content_10000,Summary:Summary_10000,Title:Title_10000,Topic:Topic_10000

202603182302230744,Request sent
202603182302231876,received 10000 data,stream length:2320001,json length:2320001
202603182302231878
First:Id:10001,Name:Name_10001,ISBN:ISBN_10001_93d4b65b35bb411a9a2d556e8a5dcd62,Author:Author_10001,Comment:Comment_10001,Content:Content_10001,Summary:Summary_10001,Title:Title_10001,Topic:Topic_10001
Last:Id:20000,Name:Name_20000,ISBN:ISBN_20000_aeda4200d5ca4864ae10d4003a1c03fd,Author:Author_20000,Comment:Comment_20000,Content:Content_20000,Summary:Summary_20000,Title:Title_20000,Topic:Topic_20000

202603182302281992,Request sent
202603182302283237,received 10000 data,stream length:2320001,json length:2320001
202603182302283240
First:Id:20001,Name:Name_20001,ISBN:ISBN_20001_f7554ac525f44687b950b1dd4b871878,Author:Author_20001,Comment:Comment_20001,Content:Content_20001,Summary:Summary_20001,Title:Title_20001,Topic:Topic_20001
Last:Id:30000,Name:Name_30000,ISBN:ISBN_30000_58516ea84b0b4a5d9edc5201281dcab2,Author:Author_30000,Comment:Comment_30000,Content:Content_30000,Summary:Summary_30000,Title:Title_30000,Topic:Topic_30000

202603182302333387,Request sent
202603182302334183,received 10000 data,stream length:2320001,json length:2320001
202603182302334187
First:Id:30001,Name:Name_30001,ISBN:ISBN_30001_d789f456edca4c788e4a9dbf29ec28dc,Author:Author_30001,Comment:Comment_30001,Content:Content_30001,Summary:Summary_30001,Title:Title_30001,Topic:Topic_30001
Last:Id:40000,Name:Name_40000,ISBN:ISBN_40000_7d824ada42184851a4091116f790439e,Author:Author_40000,Comment:Comment_40000,Content:Content_40000,Summary:Summary_40000,Title:Title_40000,Topic:Topic_40000

202603182302384345,Request sent
202603182302384956,received 10000 data,stream length:2320001,json length:2320001
202603182302384959
First:Id:40001,Name:Name_40001,ISBN:ISBN_40001_92cf68204ed3457ab071808a8bac8ffa,Author:Author_40001,Comment:Comment_40001,Content:Content_40001,Summary:Summary_40001,Title:Title_40001,Topic:Topic_40001
Last:Id:50000,Name:Name_50000,ISBN:ISBN_50000_feba3467846b4d018337155cc017f629,Author:Author_50000,Comment:Comment_50000,Content:Content_50000,Summary:Summary_50000,Title:Title_50000,Topic:Topic_50000

202603182302435087,Request sent
202603182302435749,received 10000 data,stream length:2320001,json length:2320001
202603182302435754
First:Id:50001,Name:Name_50001,ISBN:ISBN_50001_45be39b260dd4a98bf7d496e91f1ed0e,Author:Author_50001,Comment:Comment_50001,Content:Content_50001,Summary:Summary_50001,Title:Title_50001,Topic:Topic_50001
Last:Id:60000,Name:Name_60000,ISBN:ISBN_60000_60d3726c14534fe89e9da3b3b74bf903,Author:Author_60000,Comment:Comment_60000,Content:Content_60000,Summary:Summary_60000,Title:Title_60000,Topic:Topic_60000

202603182302485785,Request sent
202603182302486317,received 10000 data,stream length:2320001,json length:2320001
202603182302486319
First:Id:60001,Name:Name_60001,ISBN:ISBN_60001_ae2a8d6dbf0f46d4ae8f90979ce038e5,Author:Author_60001,Comment:Comment_60001,Content:Content_60001,Summary:Summary_60001,Title:Title_60001,Topic:Topic_60001
Last:Id:70000,Name:Name_70000,ISBN:ISBN_70000_f23377f21049465ab11c55514ae1105e,Author:Author_70000,Comment:Comment_70000,Content:Content_70000,Summary:Summary_70000,Title:Title_70000,Topic:Topic_70000

202603182302536437,Request sent
202603182302537190,received 10000 data,stream length:2320001,json length:2320001
202603182302537193
First:Id:70001,Name:Name_70001,ISBN:ISBN_70001_af95903765f24f90a975c2cf3c4792db,Author:Author_70001,Comment:Comment_70001,Content:Content_70001,Summary:Summary_70001,Title:Title_70001,Topic:Topic_70001
Last:Id:80000,Name:Name_80000,ISBN:ISBN_80000_55daa06e62774cf08121053eb93edb3b,Author:Author_80000,Comment:Comment_80000,Content:Content_80000,Summary:Summary_80000,Title:Title_80000,Topic:Topic_80000

202603182302587364,Request sent
202603182302588616,received 10000 data,stream length:2320001,json length:2320001
202603182302588619
First:Id:80001,Name:Name_80001,ISBN:ISBN_80001_2378d5a0e38a41ba96d5dc6a9190ad27,Author:Author_80001,Comment:Comment_80001,Content:Content_80001,Summary:Summary_80001,Title:Title_80001,Topic:Topic_80001
Last:Id:90000,Name:Name_90000,ISBN:ISBN_90000_dea920a090c8458eb015dbe7206931ad,Author:Author_90000,Comment:Comment_90000,Content:Content_90000,Summary:Summary_90000,Title:Title_90000,Topic:Topic_90000

202603182303038672,Request sent
202603182303039099,received 10000 data,stream length:2320010,json length:2320010
202603182303039102
First:Id:90001,Name:Name_90001,ISBN:ISBN_90001_01dcb1c8e81d41b58a0c649908f19064,Author:Author_90001,Comment:Comment_90001,Content:Content_90001,Summary:Summary_90001,Title:Title_90001,Topic:Topic_90001
Last:Id:100000,Name:Name_100000,ISBN:ISBN_100000_0a50143a8a294cbb927b2ab3d50a24dc,Author:Author_100000,Comment:Comment_100000,Content:Content_100000,Summary:Summary_100000,Title:Title_100000,Topic:Topic_100000

202603182303089116,Request sent
202603182303089965,received 10000 data,stream length:2410001,json length:2410001
202603182303089967
First:Id:100001,Name:Name_100001,ISBN:ISBN_100001_535079295e404f3ca3d39f7b4098caf0,Author:Author_100001,Comment:Comment_100001,Content:Content_100001,Summary:Summary_100001,Title:Title_100001,Topic:Topic_100001
Last:Id:110000,Name:Name_110000,ISBN:ISBN_110000_bc1e764777e842a19c65a5ad63654960,Author:Author_110000,Comment:Comment_110000,Content:Content_110000,Summary:Summary_110000,Title:Title_110000,Topic:Topic_110000

 

 

image

 

posted @ 2026-03-18 22:47  FredGrit  阅读(6)  评论(0)    收藏  举报