最近研究.net core 的各种高性能类型,内存池之类的东西,基于kestrel 服务器的websocket ,写个例子练下手

把原生的Websocket用ArrayPool<T>,Memory<T>改造了下,减少服务器gc压力

源码:https://github.com/LIFICN/KestrelWebSocketServer

控制台简单调用:

        public static IConfigurationRoot configuration { get => SettingTool.AddServerOptionsJsonFile(); }

        public static async Task Main(string[] args)
        {
            var ip = configuration.GetValue<string>("ServerOptions:IP");
            var port = configuration.GetValue<int>("ServerOptions:Port");
            var path = configuration.GetValue<string>("ServerOptions:Path");
            var server = new WebSocketServer();

            WebSocketServer.EnabledLargeFileReceive = false;   // you want to receive large file, you have to set true
            WebSocketServer.ReceiveBufferSize = 4 * 1024;     //4kb
            await server.BuildAsync(ip, port, path, config =>
            {
                config.OnOpen = (connection, websocket) =>
                {
                    var id = connection.Id;
                    Console.WriteLine($"{id} Opened");
                };
                config.OnMessage = async (connection, webSocket, msg) =>
                {
                    var id = connection.Id;
                    Console.WriteLine($"Received {id}: {msg}");

                    await webSocket.SendAsync(msg);
                };
                config.OnBinary = async (connection, webSocket, file) =>
                {
                    var id = connection.Id;
                    Console.WriteLine($"{id} Binary");

                    using (FileStream fileStream = new FileStream("your file path", FileMode.Create))
                    {
                        await fileStream.WriteAsync(file);
                        fileStream.Flush();
                    }
                };
                config.OnClose = (connection, webSocket) =>
                {
                    var id = connection.Id;
                    Console.WriteLine($"{id} Closed");
                };
            });

            Console.ReadLine();
        }

  

版权声明:本文为LIFICN原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/LIFICN/p/12196542.html