最近研究.net core 的各种高性能类型,内存池之类的东西,基于kestrel 服务器的websocket ,写个例子练下手
把原生的Websocket用ArrayPool,Memory改造了下,减少服务器gc压力
控制台简单调用:
public static IConfigurationRoot configuration { get => SettingTool.AddServerOptionsJsonFile(); }
public static async Task Main(string[] args)
{
var ip = configuration.GetValue("ServerOptions:IP");
var port = configuration.GetValue("ServerOptions:Port");
var path = configuration.GetValue("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();
}