Ejemplo n.º 1
0
		public static AppFunc Middleware(AppFunc app)
		{
			return env =>
			{
				var request = new OwinRequest(env);
				var websocketVersion = request.Get<string>(OwinConstants.WebSocket.Version);
				WebSocketAccept webSocketAccept = request.Get<WebSocketAccept>(OwinConstants.WebSocket.Accept);

				if (request.CanUpgrade && websocketVersion == null) // If we have opaque support and no WebSocket support yet
				{
					if (IsWebSocketRequest(env))
					{
						// TODO: check for correct requested version of WebSocket protocol
						IDictionary<string, object> acceptOptions = null;
						WebSocketFunc webSocketFunc = null;

						// Announce websocket support
						env[OwinConstants.WebSocket.Accept] = new WebSocketAccept(
							(options, callback) =>
							{
								acceptOptions = options;
								webSocketFunc = callback;
								env[OwinConstants.ResponseStatusCode] = 101;
							});


						return app(env).ContinueWith(t =>
						{
							OwinResponse response = new OwinResponse(env);
							if (response.StatusCode == 101
								&& webSocketFunc != null)
							{
								SetWebSocketResponseHeaders(env, acceptOptions);

								request.UpgradeDelegate(acceptOptions, opaqueEnv =>
								{
									WebSocketLayer webSocket = new WebSocketLayer(opaqueEnv);
									return webSocketFunc(webSocket.Environment)
										.ContinueWith(tt => webSocket.CleanupAsync());
								});
							}
						});
					}
				}

				// else
				return app(env);
			};
		}