You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.1 KiB
68 lines
2.1 KiB
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 |
|
{ /// <summary> |
|
/// webSocket |
|
/// </summary> |
|
public class WebSocketMiddleware |
|
{ |
|
#region Identity |
|
private static Dictionary<string, WebSocket> CONNECT_POOL = new Dictionary<string, WebSocket>();//用户连接池 |
|
private readonly RequestDelegate _next; |
|
App_Sys_UserModel _userdata = new App_Sys_UserModel();//当前用户 |
|
Result result = new Result(); |
|
public WebSocketMiddleware(User user) |
|
{ |
|
_userdata = user.Userdata(); |
|
} |
|
|
|
#endregion |
|
/// <summary> |
|
/// 构造 |
|
/// </summary> |
|
/// <param name="next"></param> |
|
/// <param name="actionPathName">目标路径</param> |
|
public WebSocketMiddleware(RequestDelegate next) |
|
{ |
|
_next = next; |
|
} |
|
/// <summary> |
|
/// 中间件调用 |
|
/// </summary> |
|
/// <param name="httpContext"></param> |
|
/// <returns></returns> |
|
[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); |
|
} |
|
} |
|
}
|
|
|