public WebSocket(string WSSID) { this.WSSID = WSSID; this.WebSocketOptions = new AspNetWebSocketOptions() { SubProtocol = "potioncommotion", RequireSameOrigin = true }; }
private void DoWebSocketUpgrade(IDictionary <string, object> acceptOptions, WebSocketFunc webSocketFunc) { if (webSocketFunc == null) { throw new ArgumentNullException("webSocketFunc"); } _env.ResponseStatusCode = 101; _webSocketFunc = webSocketFunc; var options = new AspNetWebSocketOptions(); options.SubProtocol = GetWebSocketSubProtocol(_env, acceptOptions); OnStart(); _httpContext.AcceptWebSocketRequest(AcceptCallback, options); }
public void ProcessRequest(HttpContext context) { _replyWithPartialMessages = context.Request.Url.Query.Contains("replyWithPartialMessages"); string subProtocol = context.Request.QueryString["subprotocol"]; if (context.Request.Url.Query.Contains("delay10sec")) { Thread.Sleep(10000); } try { if (!context.IsWebSocketRequest) { context.Response.StatusCode = 200; context.Response.ContentType = "text/plain"; context.Response.Write("Not a websocket request"); return; } if (!string.IsNullOrEmpty(subProtocol)) { var wsOptions = new AspNetWebSocketOptions(); wsOptions.SubProtocol = subProtocol; context.AcceptWebSocketRequest(ProcessWebSocketRequest, wsOptions); } else { context.AcceptWebSocketRequest(ProcessWebSocketRequest); } } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.StatusDescription = ex.Message; } }
public override void AcceptWebSocketRequest(Func <AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options) { _inner.AcceptWebSocketRequest(userFunc, options); }
public override void AcceptWebSocketRequest(Func <AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options) { throw new NotSupportedException(NotSupportedMessage); }
/// <summary> /// Initiates an asynchronous call to the HTTP handler. /// </summary> /// /// <returns> /// An <see cref="T:System.IAsyncResult"/> that contains information about the status of the process. /// </returns> /// <param name="context">An <see cref="T:System.Web.HttpContextBase"/> object that provides references to intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param> /// <param name="callback">The <see cref="T:System.AsyncCallback"/> to call when the asynchronous method call is complete. If <paramref name="callback"/> is null, the delegate is not called. </param> /// <param name="state">Any extra data needed to process the request. </param> public IAsyncResult BeginProcessRequest(HttpContextBase context, AsyncCallback callback, object state) { var tcs = new TaskCompletionSource <Action>(state); if (callback != null) { tcs.Task.ContinueWith(task => callback(task), TaskContinuationOptions.ExecuteSynchronously); } var request = context.Request; var response = context.Response; response.BufferOutput = false; var pathBase = request.ApplicationPath; if (pathBase == "/" || pathBase == null) { pathBase = string.Empty; } if (root != null) { pathBase += root; } var path = request.Path; if (path.StartsWith(pathBase)) { path = path.Substring(pathBase.Length); } var serverVarsToAddToEnv = request.ServerVariables.AllKeys .Where(key => !key.StartsWith("HTTP_") && !string.Equals(key, "ALL_HTTP") && !string.Equals(key, "ALL_RAW")) .Select(key => new KeyValuePair <string, object>(key, request.ServerVariables.Get(key))); var env = new Dictionary <string, object>(); env[OwinConstants.Version] = "1.0"; env[OwinConstants.RequestMethod] = request.HttpMethod; env[OwinConstants.RequestScheme] = request.Url.Scheme; env[OwinConstants.RequestPathBase] = pathBase; env[OwinConstants.RequestPath] = path; env[OwinConstants.RequestQueryString] = request.ServerVariables["QUERY_STRING"]; env[OwinConstants.RequestProtocol] = request.ServerVariables["SERVER_PROTOCOL"]; env[OwinConstants.RequestBody] = request.InputStream; env[OwinConstants.RequestHeaders] = request.Headers.AllKeys .ToDictionary(x => x, x => request.Headers.GetValues(x), StringComparer.OrdinalIgnoreCase); if (request.ClientCertificate != null && request.ClientCertificate.Certificate.Length != 0) { env[OwinConstants.ClientCertificate] = new X509Certificate(request.ClientCertificate.Certificate); } env[OwinConstants.CallCancelled] = CancellationToken.None; env[OwinConstants.ResponseHeaders] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase); int?responseStatusCode = null; env[OwinConstants.ResponseBody] = new TriggerStream(response.OutputStream) { OnFirstWrite = () => { responseStatusCode = Get <int>(env, OwinConstants.ResponseStatusCode, 200); response.StatusCode = responseStatusCode.Value; object reasonPhrase; if (env.TryGetValue(OwinConstants.ResponseReasonPhrase, out reasonPhrase)) { response.StatusDescription = Convert.ToString(reasonPhrase); } var responseHeaders = Get <IDictionary <string, string[]> >(env, OwinConstants.ResponseHeaders, null); if (responseHeaders != null) { foreach (var responseHeader in responseHeaders) { foreach (var headerValue in responseHeader.Value) { response.AddHeader(responseHeader.Key, headerValue); } } } } }; SetEnvironmentServerVariables(env, serverVarsToAddToEnv); env[OwinConstants.HttpContextBase] = context; #if ASPNET_WEBSOCKETS WebSocketFunc webSocketFunc = null; IDictionary <string, object> wsAcceptOptions = null; try { // might not be implemented when using custom contexts // so catch NotImplementedException if (context.IsWebSocketRequest) { env[OwinConstants.WebSocketAcceptKey] = new WebSocketAccept( (options, wsCallback) => { env[OwinConstants.ResponseStatusCode] = 101; wsAcceptOptions = options; webSocketFunc = wsCallback; }); } } catch (NotImplementedException) { } #endif try { appFunc(env) .ContinueWith(t => { if (t.IsFaulted) { tcs.TrySetException(t.Exception.InnerExceptions); } else if (t.IsCanceled) { tcs.TrySetCanceled(); } else { #if ASPNET_WEBSOCKETS responseStatusCode = Get <int>(env, OwinConstants.ResponseStatusCode, 200); if (webSocketFunc != null && responseStatusCode == 101) { var options = new AspNetWebSocketOptions(); options.SubProtocol = GetSubProtocol(env, wsAcceptOptions); context.AcceptWebSocketRequest(async websocketContext => { var webSocket = websocketContext.WebSocket; var wsEnv = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); wsEnv[OwinConstants.WebSocketSendAsyncKey] = WebSocketSendAsync(webSocket); wsEnv[OwinConstants.WebSocketReceiveAsyncKey] = WebSocketReceiveAsync(webSocket); wsEnv[OwinConstants.WebSocketCloseAsyncKey] = WebSocketCloseAsync(webSocket); wsEnv[OwinConstants.WebSocketVersion] = "1.0"; wsEnv[OwinConstants.WebSocketCallCancelled] = CancellationToken.None; wsEnv[OwinConstants.WebSocketContext] = websocketContext; await webSocketFunc(wsEnv); switch (webSocket.State) { case WebSocketState.Closed: // closed gracefully, no action needed case WebSocketState.Aborted: // closed abortively, no action needed break; case WebSocketState.CloseReceived: await webSocket.CloseAsync(webSocket.CloseStatus ?? WebSocketCloseStatus.NormalClosure, webSocket.CloseStatusDescription ?? string.Empty, CancellationToken.None); break; case WebSocketState.Open: case WebSocketState.CloseSent: // No close received, abort so we don't have to drain the pipe. websocketContext.WebSocket.Abort(); break; default: throw new ArgumentOutOfRangeException("state", webSocket.State, string.Empty); } response.Close(); }, options); } #endif tcs.TrySetResult(() => { }); } }); } catch (Exception ex) { tcs.TrySetException(ex); } return(tcs.Task); }
public virtual void AcceptWebSocketRequest(Func <AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options) { throw new NotImplementedException(); }
public WebSocketResult(Func <AspNetWebSocketContext, Task> socketHandler, AspNetWebSocketOptions options = null) { SocketHandler = socketHandler; Options = options; }