using Elight.Entity; using Elight.Utility.Code; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading.Tasks; namespace Elight.Utility { /// /// webSocket /// public class WebSocketMiddleware { #region Identity private static Dictionary CONNECT_POOL = new Dictionary();//用户连接池 private readonly RequestDelegate _next; App_Sys_UserModel _userdata = new App_Sys_UserModel();//当前用户 Result result = new Result(); public WebSocketMiddleware(User user) { _userdata = user.Userdata(); } #endregion /// /// 构造 /// /// /// 目标路径 public WebSocketMiddleware(RequestDelegate next) { _next = next; } /// /// 中间件调用 /// /// /// [HttpGet("/ws")] public async Task Invoke(HttpContext httpContext) { try { var socket = await httpContext.WebSockets.AcceptWebSocketAsync(); string user = _userdata.Id; #region 用户添加连接池 //第一次open时,添加到连接池中 if (!CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Add(user, socket);//不存在,添加 else if (socket != CONNECT_POOL[user])//当前对象不一致,更新 CONNECT_POOL[user] = socket; #endregion } catch (Exception ex) { var ss = ex.Message; } await _next(httpContext); } } }