public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { if (_serverIsRunning) { if (context.Request.Path == "/micro/ws" && context.WebSockets.IsWebSocketRequest) { var socket = await context.WebSockets.AcceptWebSocketAsync(); var completion = new TaskCompletionSource <object>(); var client = new WebSocketClient(socket, _loggerFactory, completion); client.OnClose += (key, websocket) => Clients.TryRemove(key, out _); client.OnReceive += async buffer => { var sender = new WebSocketMessageSender(client.Socket, _messageCodec, _address.Gzip); try { var invokeMessage = await _messageCodec.DecodeAsync <InvokeMessage>(buffer, _address.Gzip); await _listener.OnReceived(sender, invokeMessage); } catch (Exception ex) { _logger.LogError(ex, $"接收消息异常:{ex.Message}"); } }; Clients.TryAdd(client.SocketId, client); _logger.LogInformation($"Socket {client.SocketId}: New connection."); // TaskCompletionSource<> is used to keep the middleware pipeline alive; // SocketProcessingLoop calls TrySetResult upon socket termination _ = Task.Run(() => client.ReceiveAsync(SocketLoopTokenSource.Token).ConfigureAwait(false)); await completion.Task; } } else { context.Response.StatusCode = 409; } } catch (Exception ex) { // HTTP 500 Internal server error context.Response.StatusCode = 500; //Program.ReportException(ex); } finally { // if this middleware didn't handle the request, pass it on if (!context.Response.HasStarted) { await next(context); } } }
private async Task OnReceived(IMessageSender sender, HttpContext context) { var input = context.Request.Body; if (input.CanSeek) { input.Seek(0, SeekOrigin.Begin); } byte[] buffers; using (var memstream = new MemoryStream()) { await input.CopyToAsync(memstream); buffers = memstream.ToArray(); } var invoke = await _messageCodec.DecodeAsync <InvokeMessage>(buffers, _address.Gzip); invoke.Headers ??= new Dictionary <string, string>(); foreach (var(key, value) in context.Request.Headers) { invoke.Headers[key] = value; } await OnReceived(sender, invoke); }