static void ConfigureWebSocketEndpoint( IApplicationBuilder application, MqttServerService mqttServerService, MqttSettingsModel mqttSettings) { if (mqttSettings?.WebSocketEndPoint?.Enabled != true) { return; } if (string.IsNullOrEmpty(mqttSettings.WebSocketEndPoint.Path)) { return; } var webSocketOptions = new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(mqttSettings.WebSocketEndPoint.KeepAliveInterval), ReceiveBufferSize = mqttSettings.WebSocketEndPoint.ReceiveBufferSize }; if (mqttSettings.WebSocketEndPoint.AllowedOrigins?.Any() == true) { webSocketOptions.AllowedOrigins.AddRange(mqttSettings.WebSocketEndPoint.AllowedOrigins); } application.UseWebSockets(webSocketOptions); application.Use(async(context, next) => { if (context.Request.Path == mqttSettings.WebSocketEndPoint.Path) { if (context.WebSockets.IsWebSocketRequest) { string subProtocol = null; if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)) { subProtocol = MqttSubProtocolSelector.SelectSubProtocol(requestedSubProtocolValues); } using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol).ConfigureAwait(false)) { await mqttServerService.RunWebSocketConnectionAsync(webSocket, context).ConfigureAwait(false); } } else { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; } } else { await next().ConfigureAwait(false); } }); }
private static void ConfigureWebSocketEndpoint( IApplicationBuilder application, MqttServerService mqttServerService, SettingsModel settings) { if (settings?.WebSocketEndPoint?.Enabled != true) { return; } if (string.IsNullOrEmpty(settings.WebSocketEndPoint.Path)) { return; } var webSocketOptions = new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(settings.WebSocketEndPoint.KeepAliveInterval), ReceiveBufferSize = settings.WebSocketEndPoint.ReceiveBufferSize }; if (settings.WebSocketEndPoint.AllowedOrigins?.Any() == true) { webSocketOptions.AllowedOrigins.AddRange(settings.WebSocketEndPoint.AllowedOrigins); } application.UseWebSockets(webSocketOptions); application.Use(async(context, next) => { if (context.Request.Path == settings.WebSocketEndPoint.Path) { if (context.WebSockets.IsWebSocketRequest) { using (var webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false)) { await mqttServerService.RunWebSocketConnectionAsync(webSocket, context).ConfigureAwait(false); } } else { context.Response.StatusCode = 400; } } else { await next().ConfigureAwait(false); } }); }