예제 #1
0
 public WebSocketHandshake(IPEndPoint localEndpoint, IPEndPoint remoteEndpoint)
 {
     Request  = new WebSocketHttpRequest(localEndpoint, remoteEndpoint);
     Response = new WebSocketHttpResponse();
     NegotiatedMessageExtensions = new List <IWebSocketMessageExtensionContext>();
     _invalidated = false;
 }
예제 #2
0
 public WebSocketHandshake()
 {
     Request  = new WebSocketHttpRequest();
     Response = new WebSocketHttpResponse();
     NegotiatedMessageExtensions = new List <IWebSocketMessageExtensionContext>();
     _invalidated = false;
 }
 public WebSocketHandshake()
 {
     Request = new WebSocketHttpRequest();
     Response = new WebSocketHttpResponse();
     NegotiatedMessageExtensions = new List<IWebSocketMessageExtensionContext>();
     _invalidated = false;
 }
        public async Task <WebSocket> ConnectAsync([NotNull] Uri address, Headers <RequestHeader> requestHeaders = null, CancellationToken cancellation = default(CancellationToken))
        {
            try
            {
                cancellation.ThrowIfCancellationRequested();
                if (this.workCancellationSource.IsCancellationRequested)
                {
                    throw new WebSocketException("Client is currently closing or closed.");
                }

                var workCancellation        = this.workCancellationSource.Token;
                var negotiationCancellation = this.negotiationsTimeoutQueue?.GetSubscriptionList().Token ?? CancellationToken.None;

                if (cancellation.CanBeCanceled || workCancellation.CanBeCanceled || negotiationCancellation.CanBeCanceled)
                {
                    cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellation, workCancellation, negotiationCancellation).Token;
                }

                var request = new WebSocketHttpRequest(HttpRequestDirection.Outgoing)
                {
                    RequestUri = address,
                };

                if (requestHeaders != null)
                {
                    request.Headers.AddMany(requestHeaders);
                }

                var handshake      = new WebSocketHandshake(request);
                var pendingRequest = this.OpenConnectionAsync(handshake, cancellation);

                this.pendingRequests.TryAdd(handshake, pendingRequest);

                var webSocket = await pendingRequest.IgnoreFaultOrCancellation().ConfigureAwait(false);

                if (!workCancellation.IsCancellationRequested && negotiationCancellation.IsCancellationRequested)
                {
                    SafeEnd.Dispose(webSocket, this.log);
                    throw new WebSocketException("Negotiation timeout.");
                }

                if (this.pendingRequests.TryRemove(handshake, out pendingRequest) && this.workCancellationSource.IsCancellationRequested && this.pendingRequests.IsEmpty)
                {
                    this.closeEvent.Set();
                }

                webSocket = await pendingRequest.ConfigureAwait(false);

                this.pingQueue?.GetSubscriptionList().Add(webSocket);

                return(webSocket);
            }
            catch (Exception connectionError)
                when(connectionError.Unwrap() is ThreadAbortException == false &&
                     connectionError.Unwrap() is OperationCanceledException == false &&
                     connectionError.Unwrap() is WebSocketException == false)
                {
                    throw new WebSocketException($"An unknown error occurred while connection to '{address}'. More detailed information in inner exception.", connectionError.Unwrap());
                }
        }
 public WebSocketHandshake()
 {
     Request = new WebSocketHttpRequest();
     NegotiatedMessageExtensions = new List<IWebSocketMessageExtensionContext>();
     ResponseExtensions = new List<WebSocketExtension>();
     HasSubProtocolMatch = true;
     _invalidated = false;
 }
예제 #6
0
        public WebSocketHandshake([NotNull] WebSocketHttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            this.Id       = Interlocked.Increment(ref LastId);
            this.Request  = request;
            this.Response = new WebSocketHttpResponse();
            this.NegotiatedMessageExtensions = new List <IWebSocketMessageExtensionContext>();
        }
예제 #7
0
        public WebSocketFactory GetWebSocketFactory(WebSocketHttpRequest Request)
        {
            WebSocketFactory factory;

            if (_factories.TryGetValue(Request.WebSocketVersion, out factory))
            {
                return(factory);
            }
            else
            {
                return(null);
            }
        }
예제 #8
0
        protected WebSocket([NotNull] WebSocketHttpRequest request, [NotNull] WebSocketHttpResponse response)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            this.HttpRequest  = request;
            this.HttpResponse = response;
        }
예제 #9
0
        protected WebSocket(WebSocketHttpRequest request, WebSocketHttpResponse response)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            HttpRequest  = request;
            HttpResponse = response;
        }
예제 #10
0
        public bool TryGetWebSocketFactory(WebSocketHttpRequest request, out WebSocketFactory factory)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            factory = default(WebSocketFactory);
            var webSocketsVersion = default(short);

            if (short.TryParse(request.Headers[RequestHeader.WebSocketVersion], out webSocketsVersion) && this.factoryByVersion.TryGetValue(webSocketsVersion, out factory))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        private void HttpNegotiation(WebSocketHttpRequest request, WebSocketHttpResponse response)
        {
            Guid connectionId = Guid.Empty;
            if (request.RequestUri == null || request.RequestUri.OriginalString.Length < 1 || !Guid.TryParse(request.RequestUri.OriginalString.Substring(1), out connectionId))
            {
                connectionId = _sysInfo.Guid();
                _log.Info("Connection Id created: {0}", connectionId);
            }
            else
                _log.Info("Connection Id from url: {0}", connectionId);

            request.Items.Add(ConnectionIdKey, connectionId);

            Guid userId;
            if (request.Cookies[ConnectionManager.UserSessionCookieName] == null)
            {
                userId = _sysInfo.Guid();
                _log.Info("User ID created: {0}", userId);
            }
            else
            {
                userId = Guid.Parse(request.Cookies[ConnectionManager.UserSessionCookieName].Value);
                _log.Info("User ID found in cookie: {0}", userId);
            }
            
           Queue.PublishRequest(new ConnectionConnectRequest(connectionId, userId), ctx =>
            {
                ctx.HandleFault(f =>
                {
                    response.Status = HttpStatusCode.InternalServerError;
                });
                ctx.HandleTimeout(TimeSpan.FromSeconds(5), () =>
                {
                    response.Status = HttpStatusCode.RequestTimeout;
                });
                ctx.Handle<ConnectionConnectResponse>(res =>
                {
                    response.Cookies.Add(new Cookie(ConnectionManager.UserSessionCookieName, res.UserId.ToString()));
                });
            });
        }
 internal WebSocketFactory GetWebSocketFactory(WebSocketHttpRequest Request)
 => _factories.TryGetValue(Request.WebSocketVersion, out WebSocketFactory factory)
         ? factory
         : null;
예제 #13
0
 public abstract WebSocket CreateWebSocket(NetworkConnection networkConnection, WebSocketListenerOptions options, WebSocketHttpRequest httpRequest, WebSocketHttpResponse httpResponse, List <IWebSocketMessageExtensionContext> negotiatedExtensions);
예제 #14
0
 internal WebSocketHandshake()
 {
     Request      = new WebSocketHttpRequest();
     Response     = new WebSocketHttpResponse();
     _invalidated = false;
 }
 public abstract WebSocket CreateWebSocket(Stream stream, WebSocketListenerOptions options, IPEndPoint localEndpoint, IPEndPoint remoteEndpoint, WebSocketHttpRequest httpRequest, WebSocketHttpResponse httpResponse, List<IWebSocketMessageExtensionContext> negotiatedExtensions);
예제 #16
0
 public WebSocket(WebSocketHttpRequest request, WebSocketHttpResponse response)
 {
     HttpRequest  = request;
     HttpResponse = response;
 }
 public bool TryNegotiate(WebSocketHttpRequest request, out WebSocketExtension extensionResponse, out IWebSocketMessageExtensionContext context)
 {
     extensionResponse = _response;
     context           = new WebSocketDeflateContext();
     return(true);
 }
 public bool TryNegotiate(WebSocketHttpRequest request, out WebSocketExtension extensionResponse, out IWebSocketMessageExtensionContext context)
 {
     extensionResponse = Response;
     context = new WebSocketSharpDeflateContext();
     return true;
 }
예제 #19
0
 public WebSocket(WebSocketHttpRequest request, WebSocketHttpResponse response)
 {
     Guid         = Guid.NewGuid();
     HttpRequest  = request;
     HttpResponse = response;
 }
        public async Task <WebSocketHandshake> HandshakeAsync(NetworkConnection networkConnection)
        {
            if (networkConnection == null)
            {
                throw new ArgumentNullException(nameof(networkConnection));
            }

            var request = new WebSocketHttpRequest(HttpRequestDirection.Incoming)
            {
                LocalEndPoint  = networkConnection.LocalEndPoint ?? WebSocketHttpRequest.NoAddress,
                RemoteEndPoint = networkConnection.RemoteEndPoint ?? WebSocketHttpRequest.NoAddress,
                IsSecure       = networkConnection is SslNetworkConnection
            };
            var handshake = new WebSocketHandshake(request);

            try
            {
                ReadHttpRequest(networkConnection, handshake);
                if (!IsWebSocketRequestValid(handshake))
                {
                    await WriteHttpResponseAsync(handshake, networkConnection).ConfigureAwait(false);

                    return(handshake);
                }

                handshake.IsWebSocketRequest = true;

                var factory = default(WebSocketFactory);
                if (this.factories.TryGetWebSocketFactory(handshake.Request, out factory) == false)
                {
                    await WriteHttpResponseAsync(handshake, networkConnection).ConfigureAwait(false);

                    return(handshake);
                }

                handshake.Factory            = factory;
                handshake.IsVersionSupported = true;

                ConsolidateObjectModel(handshake);

                SelectExtensions(handshake);


                if (await this.RunHttpNegotiationHandlerAsync(handshake).ConfigureAwait(false) == false)
                {
                    throw new WebSocketException("HTTP authentication failed.");
                }

                await WriteHttpResponseAsync(handshake, networkConnection).ConfigureAwait(false);
            }
            catch (Exception handshakeError)
            {
                if (this.log.IsDebugEnabled)
                {
                    this.log.Debug("Failed to handshake request.", handshakeError);
                }

                handshake.Error = ExceptionDispatchInfo.Capture(handshakeError);
                if (!handshake.IsResponseSent)
                {
                    try { WriteHttpResponse(handshake, networkConnection); }
                    catch (Exception writeResponseError)
                    {
                        if (this.log.IsDebugEnabled)
                        {
                            this.log.Debug("Failed to write error response.", writeResponseError);
                        }
                    }
                }
            }
            return(handshake);
        }
예제 #21
0
 public abstract WebSocket CreateWebSocket(Stream stream, WebSocketListenerOptions options, IPEndPoint localEndpoint, IPEndPoint remoteEndpoint, WebSocketHttpRequest httpRequest, WebSocketHttpResponse httpResponse, List <IWebSocketMessageExtensionContext> negotiatedExtensions);
예제 #22
0
 public WebSocket(WebSocketHttpRequest request, WebSocketHttpResponse response)
 {
     HttpRequest = request;
     HttpResponse = response;
 }