Exemplo n.º 1
0
 public async Task Invoke(HttpContext context)
 {
     if (context.WebSockets.IsWebSocketRequest)
     {
         ws = ToolsFactory.GetWebSocket(context);
         if (ws == null)
         {
             throw new ResultException("不支持WebSocket连接");
         }
         //后台成功接收到连接请求并建立连接后,前台的webSocket.onopen = function (event){}才执行
         WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(true);;
         Dictionary <string, string> data = context.Request.Query.ToDictionary(t => t.Key, t => t.Value.ToString());
         if (!data.ContainsKey("IP"))
         {
             data.Add("IP", IPAgent.GetIP(context));
         }
         if (!data.ContainsKey("IPAddress"))
         {
             data.Add("IPAddress", IPAgent.GetAddress(IPAgent.GetIP(context)));
         }
         wsClient = ws.Register(new WebSocketClient
         {
             ID        = Guid.NewGuid(),
             WebSocket = webSocket,
             Query     = data
         });
         try
         {
             await Handler(wsClient);
         }
         catch (Exception ex)
         {
             await context.Response.WriteAsync(ex.Message).ConfigureAwait(true);;
         }
         finally
         {
             ws.Remove(wsClient);
         }
     }
     else
     {
         await _next(context).ConfigureAwait(true);
     }
 }
Exemplo n.º 2
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     app
     .UseCors(builder =>
     {
         builder.WithOrigins("*");
         builder.AllowAnyHeader();
         builder.AllowAnyMethod();
     })
     .UseWebSockets(new WebSocketOptions
     {
         KeepAliveInterval = TimeSpan.FromMinutes(1)
     })
     .UseStaticFiles()
     .UseHttpContext()
     .UseMiddleware <WebSocketMiddleware>()
     .UseMiddleware <ToolsExceptionMIddleware>()
     .Run(async(context) =>
     {
         await ToolsFactory.Invote(context).WriteAsync(context).ConfigureAwait(true);
     });
 }