public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path == "/ws")
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                    SocketPool.Add(webSocket);

                    try
                    {
                        await Handle(context, webSocket);
                    }
                    catch (Exception ex)
                    {
                        await context.Response.WriteAsync("closed");
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            else
            {
                await _next(context);
            }
        }
        private async Task Handle(HttpContext context, WebSocket client)
        {
            var buffer = new byte[1024 * 2];
            WebSocketReceiveResult result = null;

            do
            {
                result = await client.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                var message = await ConvertWebsocketMessage(result, buffer);

                Console.WriteLine(message);
            }while (!result.CloseStatus.HasValue);

            SocketPool.Remove(client);
        }
Beispiel #3
0
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .ConfigureAppConfiguration((context, config) =>
 {
     //new一个client实例
     //使用无参构造函数会自动读取本地appsettings.json文件的AgileConfig节点的配置
     var configClient = new ConfigClient();
     //使用AddAgileConfig配置一个新的IConfigurationSource
     config.AddAgileConfig(configClient);
     //找一个变量挂载client实例,以便其他地方可以直接使用实例访问配置
     ConfigClient = configClient;
     //注册配置项修改事件
     configClient.ConfigChanged += (arg) =>
     {
         Console.WriteLine($"action:{arg.Action} key:{arg.Key}");
         SocketPool.SendMessage("reload");
     };
 })
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
 });