Exemplo n.º 1
0
 public ConnectionHolder(Log log, HttpClientConnectionManager manager, HttpClientConnection
                         managedConn) : base()
 {
     this.log         = log;
     this.manager     = manager;
     this.managedConn = managedConn;
 }
 /// <summary>Sends the request and obtain a response.</summary>
 /// <remarks>Sends the request and obtain a response.</remarks>
 /// <param name="request">the request to execute.</param>
 /// <param name="conn">the connection over which to execute the request.</param>
 /// <returns>the response to the request.</returns>
 /// <exception cref="System.IO.IOException">in case of an I/O error.</exception>
 /// <exception cref="Org.Apache.Http.HttpException">
 /// in case of HTTP protocol violation or a processing
 /// problem.
 /// </exception>
 public virtual HttpResponse Execute(IHttpRequest request, HttpClientConnection conn
                                     , HttpContext context)
 {
     Args.NotNull(request, "HTTP request");
     Args.NotNull(conn, "Client connection");
     Args.NotNull(context, "HTTP context");
     try
     {
         HttpResponse response = DoSendRequest(request, conn, context);
         if (response == null)
         {
             response = DoReceiveResponse(request, conn, context);
         }
         return(response);
     }
     catch (IOException ex)
     {
         CloseConnection(conn);
         throw;
     }
     catch (HttpException ex)
     {
         CloseConnection(conn);
         throw;
     }
     catch (RuntimeException ex)
     {
         CloseConnection(conn);
         throw;
     }
 }
Exemplo n.º 3
0
        private void OnHttpRequestTimeout(object state)
        {
            try
            {
                HttpClientConnection clientConnection = (HttpClientConnection)state;
                if (clientConnection == null)
                {
                    return;
                }

                int    actionId = 0;
                string action;
                if (clientConnection.Param.TryGetValue("ActionId", out action))
                {
                    actionId = action.ToInt();
                }

                var httpresponse = new SocketGameResponse();
                ActionFactory.RequestError(httpresponse, actionId, "Request Timeout.");
                byte[] respData = httpresponse.ReadByte();
                OnHttpResponse(clientConnection, respData, 0, respData.Length);
            }
            catch
            {
            }
        }
 /// <summary>
 /// Implements chunked transfer encoding, as defined in §3.6.1 RFC 2616.
 /// </summary>
 /// <param name="Output">Decoded output.</param>
 /// <param name="ChunkSize">Chunk size.</param>
 /// <param name="ClientConnection">Client conncetion.</param>
 internal ChunkedTransferEncoding(IBinaryTransmission Output, int ChunkSize, HttpClientConnection ClientConnection)
     : base(Output, ClientConnection)
 {
     this.chunkSize = ChunkSize;
     this.chunk     = new byte[ChunkSize];
     this.pos       = 0;
 }
Exemplo n.º 5
0
 internal WebSocket(WebSocketListener WebSocketListener, HttpRequest Request,
                    HttpResponse Response)
 {
     this.listener     = WebSocketListener;
     this.httpRequest  = Request;
     this.httpResponse = Response;
     this.connection   = Request.clientConnection;
 }
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Upgrade(HttpClientConnection conn, HttpRoute route, HttpContext
                             context)
 {
     Args.NotNull(conn, "Connection");
     Args.NotNull(route, "HTTP route");
     Asserts.Check(conn == this.conn, "Connection not obtained from this manager");
     this.connectionOperator.Upgrade(this.conn, route.GetTargetHost(), context);
 }
 public virtual void ReleaseConnection(HttpClientConnection conn, object state, long
                                       keepalive, TimeUnit tunit)
 {
     lock (this)
     {
         Args.NotNull(conn, "Connection");
         Asserts.Check(conn == this.conn, "Connection not obtained from this manager");
         if (this.log.IsDebugEnabled())
         {
             this.log.Debug("Releasing connection " + conn);
         }
         if (this.shutdown)
         {
             ShutdownConnection();
             return;
         }
         try
         {
             this.updated = Runtime.CurrentTimeMillis();
             if (!this.conn.IsOpen())
             {
                 this.conn   = null;
                 this.route  = null;
                 this.conn   = null;
                 this.expiry = long.MaxValue;
             }
             else
             {
                 this.state = state;
                 if (this.log.IsDebugEnabled())
                 {
                     string s;
                     if (keepalive > 0)
                     {
                         s = "for " + keepalive + " " + tunit;
                     }
                     else
                     {
                         s = "indefinitely";
                     }
                     this.log.Debug("Connection can be kept alive " + s);
                 }
                 if (keepalive > 0)
                 {
                     this.expiry = this.updated + tunit.ToMillis(keepalive);
                 }
                 else
                 {
                     this.expiry = long.MaxValue;
                 }
             }
         }
         finally
         {
             this.leased = false;
         }
     }
 }
        /// <summary>Initializes an instance of the <see cref="ServiceChannelClient"/> class.</summary>
        /// <param name="connection">The HTTP client connection.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connection"/> is <see langword="null"/>.</exception>
        protected ServiceChannelClient(HttpClientConnection connection)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            ClientConnection = connection;
        }
        /// <summary>Send the given request over the given connection.</summary>
        /// <remarks>
        /// Send the given request over the given connection.
        /// <p>
        /// This method also handles the expect-continue handshake if necessary.
        /// If it does not have to handle an expect-continue handshake, it will
        /// not use the connection for reading or anything else that depends on
        /// data coming in over the connection.
        /// </remarks>
        /// <param name="request">
        /// the request to send, already
        /// <see cref="PreProcess(Org.Apache.Http.IHttpRequest, HttpProcessor, HttpContext)">preprocessed
        ///     </see>
        /// </param>
        /// <param name="conn">
        /// the connection over which to send the request,
        /// already established
        /// </param>
        /// <param name="context">the context for sending the request</param>
        /// <returns>
        /// a terminal response received as part of an expect-continue
        /// handshake, or
        /// <code>null</code> if the expect-continue handshake is not used
        /// </returns>
        /// <exception cref="System.IO.IOException">in case of an I/O error.</exception>
        /// <exception cref="Org.Apache.Http.HttpException">
        /// in case of HTTP protocol violation or a processing
        /// problem.
        /// </exception>
        protected internal virtual HttpResponse DoSendRequest(IHttpRequest request, HttpClientConnection
                                                              conn, HttpContext context)
        {
            Args.NotNull(request, "HTTP request");
            Args.NotNull(conn, "Client connection");
            Args.NotNull(context, "HTTP context");
            HttpResponse response = null;

            context.SetAttribute(HttpCoreContext.HttpConnection, conn);
            context.SetAttribute(HttpCoreContext.HttpReqSent, false);
            conn.SendRequestHeader(request);
            if (request is HttpEntityEnclosingRequest)
            {
                // Check for expect-continue handshake. We have to flush the
                // headers and wait for an 100-continue response to handle it.
                // If we get a different response, we must not send the entity.
                bool            sendentity = true;
                ProtocolVersion ver        = request.GetRequestLine().GetProtocolVersion();
                if (((HttpEntityEnclosingRequest)request).ExpectContinue() && !ver.LessEquals(HttpVersion
                                                                                              .Http10))
                {
                    conn.Flush();
                    // As suggested by RFC 2616 section 8.2.3, we don't wait for a
                    // 100-continue response forever. On timeout, send the entity.
                    if (conn.IsResponseAvailable(this.waitForContinue))
                    {
                        response = conn.ReceiveResponseHeader();
                        if (CanResponseHaveBody(request, response))
                        {
                            conn.ReceiveResponseEntity(response);
                        }
                        int status = response.GetStatusLine().GetStatusCode();
                        if (status < 200)
                        {
                            if (status != HttpStatus.ScContinue)
                            {
                                throw new ProtocolException("Unexpected response: " + response.GetStatusLine());
                            }
                            // discard 100-continue
                            response = null;
                        }
                        else
                        {
                            sendentity = false;
                        }
                    }
                }
                if (sendentity)
                {
                    conn.SendRequestEntity((HttpEntityEnclosingRequest)request);
                }
            }
            conn.Flush();
            context.SetAttribute(HttpCoreContext.HttpReqSent, true);
            return(response);
        }
Exemplo n.º 10
0
        public static CPoolEntry GetPoolEntry(HttpClientConnection proxy)
        {
            CPoolEntry entry = GetHandler(proxy).GetPoolEntry();

            if (entry == null)
            {
                throw new ConnectionShutdownException();
            }
            return(entry);
        }
 private static void CloseConnection(HttpClientConnection conn)
 {
     try
     {
         conn.Close();
     }
     catch (IOException)
     {
     }
 }
Exemplo n.º 12
0
        public void Calling_Refresh_UsingHttpClientConnection_DoesNotThrow()
        {
            var settings = ElasticsearchConfiguration.Settings()
                           .EnableCompressedResponses(true);
            var connection = new HttpClientConnection(settings);
            var client     = new ElasticClient(settings, connection: connection);

            Assert.DoesNotThrow(() => client.Refresh());
            Assert.DoesNotThrow(() => client.Get <ElasticsearchProject>(NestTestData.Data.First().Id));
            Assert.DoesNotThrow(() => client.Ping());
        }
Exemplo n.º 13
0
 /// <exception cref="System.Exception"></exception>
 public virtual object Invoke(object proxy, MethodInfo method, object[] args)
 {
     if (method.Equals(CloseMethod))
     {
         Close();
         return(null);
     }
     else
     {
         if (method.Equals(ShutdownMethod))
         {
             Shutdown();
             return(null);
         }
         else
         {
             if (method.Equals(IsOpenMethod))
             {
                 return(Sharpen.Extensions.ValueOf(IsOpen()));
             }
             else
             {
                 if (method.Equals(IsStaleMethod))
                 {
                     return(Sharpen.Extensions.ValueOf(IsStale()));
                 }
                 else
                 {
                     HttpClientConnection conn = GetConnection();
                     if (conn == null)
                     {
                         throw new ConnectionShutdownException();
                     }
                     try
                     {
                         return(method.Invoke(conn, args));
                     }
                     catch (TargetInvocationException ex)
                     {
                         Exception cause = ex.InnerException;
                         if (cause != null)
                         {
                             throw cause;
                         }
                         else
                         {
                             throw;
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 14
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void RouteComplete(HttpClientConnection managedConn, HttpRoute route
                                   , HttpContext context)
 {
     Args.NotNull(managedConn, "Managed Connection");
     Args.NotNull(route, "HTTP route");
     lock (managedConn)
     {
         CPoolEntry entry = CPoolProxy.GetPoolEntry(managedConn);
         entry.MarkRouteComplete();
     }
 }
Exemplo n.º 15
0
        private static Apache.Http.Impl.Conn.CPoolProxy GetHandler(HttpClientConnection proxy
                                                                   )
        {
            InvocationHandler handler = Proxy.GetInvocationHandler(proxy);

            if (!typeof(Apache.Http.Impl.Conn.CPoolProxy).IsInstanceOfType(handler))
            {
                throw new InvalidOperationException("Unexpected proxy handler class: " + handler);
            }
            return(typeof(Apache.Http.Impl.Conn.CPoolProxy).Cast(handler));
        }
Exemplo n.º 16
0
        public virtual bool IsStale()
        {
            HttpClientConnection conn = GetConnection();

            if (conn != null)
            {
                return(conn.IsStale());
            }
            else
            {
                return(true);
            }
        }
        private SsrsDiscovery.ReportingService2010 CreateSsrsClient( )
        {
            //Get the underlying connection
            var conn = new HttpClientConnection(m_connectionManager.AcquireConnection(null));

            var proxy = new SsrsDiscovery.ReportingService2010()
            {
                Url         = Path.Combine(m_connectionManager.ConnectionString, "ReportService2010.asmx").Replace('\\', '/'),
                Credentials = conn.CreateCredentials()
            };

            return(proxy);
        }
Exemplo n.º 18
0
        private SsrsDiscovery.ReportingService2010 CreateSsrsClient(GeneralViewNode node)
        {
            //Get the underlying connection
            var cm   = ConnectionService.GetConnections().GetConnection(node.HttpConnection);
            var conn = new HttpClientConnection(cm.AcquireConnection(null));

            var proxy = new SsrsDiscovery.ReportingService2010()
            {
                Url         = Path.Combine(cm.ConnectionString, "ReportService2010.asmx").Replace('\\', '/'),
                Credentials = conn.CreateCredentials()
            };

            return(proxy);
        }
Exemplo n.º 19
0
 private void CreateTCPConnectionClick(object sender, EventArgs e)
 {
     this._tcpConnForm.ShowDialog();
     if (this._tcpConnForm.IsSaved)
     {
         bool connected = this.ConnectTCP();
         if (!connected)
         {
             ErrorBox.ShowDialog(string.Format("Cannot connect to {0}:{1}", this._tcpConnForm.Host, this._tcpConnForm.Port));
             this._currentConnection = null;
         }
         this._resendTCP.Enabled = connected;
     }
 }
Exemplo n.º 20
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Upgrade(HttpClientConnection managedConn, HttpRoute route, HttpContext
                                    context)
        {
            Args.NotNull(managedConn, "Managed Connection");
            Args.NotNull(route, "HTTP route");
            ManagedHttpClientConnection conn;

            lock (managedConn)
            {
                CPoolEntry entry = CPoolProxy.GetPoolEntry(managedConn);
                conn = entry.GetConnection();
            }
            this.connectionOperator.Upgrade(conn, route.GetTargetHost(), context);
        }
        /// <summary>Creates a credentials object for the given connection.</summary>
        /// <param name="source">The source.</param>
        /// <returns>The credentials.</returns>
        public static ICredentials CreateCredentials(this HttpClientConnection source)
        {
            if (source.UseServerCredentials)
            {
                return(CredentialCache.DefaultCredentials);
            }

            if (!String.IsNullOrWhiteSpace(source.ServerDomain))
            {
                return(new NetworkCredential(source.ServerUserName, source.GetServerPassword(), source.ServerDomain));
            }
            else
            {
                return(new NetworkCredential(source.ServerUserName, source.GetServerPassword()));
            }
        }
Exemplo n.º 22
0
        static Task <HttpClientConnection> InitHttp(ClientBootstrap client, TlsConnectionOptions tlsOptions)
        {
            var options = new HttpClientConnectionOptions();

            options.ClientBootstrap      = client;
            options.TlsConnectionOptions = tlsOptions;
            options.HostName             = ctx.Uri.Host;
            options.Port = (UInt16)ctx.Uri.Port;
            options.ConnectionShutdown += OnConnectionShutdown;
            if (ctx.ConnectTimeoutMs != 0)
            {
                var socketOptions = new SocketOptions();
                socketOptions.ConnectTimeoutMs = ctx.ConnectTimeoutMs;
                options.SocketOptions          = socketOptions;
            }
            return(HttpClientConnection.NewConnection(options));
        }
        /// <summary>Creates a basic HTTP binding from an HTTP client connection.</summary>
        /// <param name="source">The connection.</param>
        /// <returns>The binding.</returns>
        /// <remarks>
        /// The binding uses default binding settings except as indicated below.
        /// <list type="bullet">
        /// <item>BypassProxyOnLocal = true</item>
        /// </list>
        /// <para />
        /// The binding is configured to use transport security if HTTPS is specified otherwise it uses no security.
        /// <para />
        /// The binding is configured to use NTLM credentials if the connection is using a domain for credentials.
        /// </remarks>
        public static BasicHttpBinding CreateBasicHttpBinding(this HttpClientConnection source)
        {
            //source.UseSecureConnection isn't true when HTTPS is applied so parse this manually
            var uri     = new Uri(source.ServerURL);
            var binding = uri.Scheme == "https" ? new BasicHttpBinding(BasicHttpSecurityMode.Transport) : new BasicHttpBinding(BasicHttpSecurityMode.None);

            binding.BypassProxyOnLocal = true;

            if (source.UseWindowsCredentials())
            {
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
                //binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            }
            ;

            return(binding);
        }
Exemplo n.º 24
0
        public override void Start()
        {
            IsBusy = true;

            _upStreamConnection = new HttpClientConnection(_forwardingHost, _forwardingPort, _isSecure);
            if (_upStreamConnection.Connect())
            {
                base.Start();
            }
            else
            {
                HttpServerConsole.Instance.WriteLine(LogMessageType.Information,
                                                     "Could not establish connection to {0}:{1}",
                                                     _forwardingHost, _forwardingPort);
                Close();
                IsBusy = false;
            }
        }
Exemplo n.º 25
0
        private bool ConnectTCP()
        {
            bool connected = false;

            if (this._currentConnection != null)
            {
                this._currentConnection.Close();
            }
            this._isReading = false;
            int port;

            if (int.TryParse(this._tcpConnForm.Port, out port))
            {
                this._currentConnection = new HttpClientConnection(this._tcpConnForm.Host, port, this._tcpConnForm.IsSecure);
                connected = this._currentConnection.Connect();
            }
            return(connected);
        }
Exemplo n.º 26
0
 public virtual void ReleaseConnection(HttpClientConnection managedConn, object state
                                       , long keepalive, TimeUnit tunit)
 {
     Args.NotNull(managedConn, "Managed connection");
     lock (managedConn)
     {
         CPoolEntry entry = CPoolProxy.Detach(managedConn);
         if (entry == null)
         {
             return;
         }
         ManagedHttpClientConnection conn = entry.GetConnection();
         try
         {
             if (conn.IsOpen())
             {
                 entry.SetState(state);
                 entry.UpdateExpiry(keepalive, tunit != null ? tunit : TimeUnit.Milliseconds);
                 if (this.log.IsDebugEnabled())
                 {
                     string s;
                     if (keepalive > 0)
                     {
                         s = "for " + (double)keepalive / 1000 + " seconds";
                     }
                     else
                     {
                         s = "indefinitely";
                     }
                     this.log.Debug("Connection " + Format(entry) + " can be kept alive " + s);
                 }
             }
         }
         finally
         {
             this.pool.Release(entry, conn.IsOpen() && entry.IsRouteComplete());
             if (this.log.IsDebugEnabled())
             {
                 this.log.Debug("Connection released: " + Format(entry) + FormatStats(entry.GetRoute
                                                                                          ()));
             }
         }
     }
 }
Exemplo n.º 27
0
 private void OnHttpRequestTimeout(object state)
 {
     try
     {
         HttpClientConnection clientConnection = (HttpClientConnection)state;
         if (clientConnection == null)
         {
             return;
         }
         var actionGetter = clientConnection.ActionGetter;
         clientConnection.GameResponse.WriteError(actionGetter, Language.Instance.ErrorCode, "Request Timeout.");
         byte[] respData = clientConnection.GameResponse.ReadByte();
         OnHttpResponse(clientConnection, respData, 0, respData.Length);
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("OnHttpRequestTimeout:{0}", ex);
     }
 }
        /// <summary>Sets the client credentials on a WCF client.</summary>
        /// <typeparam name="T">The service interface.</typeparam>
        /// <param name="source">The client.</param>
        /// <param name="connection">The HTTP connection.</param>
        /// <remarks>
        /// Both Windows and basic credentials are supported.
        /// </remarks>
        public static void SetClientCredentials <T> (this ClientBase <T> source, HttpClientConnection connection) where T : class
        {
            //Windows
            if (connection.UseWindowsCredentials())
            {
                var creds = source.ClientCredentials.Windows;

                creds.ClientCredential.UserName = connection.ServerUserName;
                creds.ClientCredential.Password = connection.GetServerPassword();
                creds.ClientCredential.Domain   = connection.ServerDomain;
            }
            else if (!String.IsNullOrWhiteSpace(connection.ServerUserName))
            {
                var creds = source.ClientCredentials;

                creds.UserName.UserName = connection.ServerUserName;
                creds.UserName.Password = connection.GetServerPassword();
            }
            ;
        }
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Connect(HttpClientConnection conn, HttpRoute route, int connectTimeout
                                    , HttpContext context)
        {
            Args.NotNull(conn, "Connection");
            Args.NotNull(route, "HTTP route");
            Asserts.Check(conn == this.conn, "Connection not obtained from this manager");
            HttpHost host;

            if (route.GetProxyHost() != null)
            {
                host = route.GetProxyHost();
            }
            else
            {
                host = route.GetTargetHost();
            }
            IPEndPoint localAddress = route.GetLocalSocketAddress();

            this.connectionOperator.Connect(this.conn, host, localAddress, connectTimeout, this
                                            .socketConfig, context);
        }
Exemplo n.º 30
0
        static Task <StreamResult> InitStream(HttpClientConnection connection)
        {
            var headers = new List <HttpHeader>();

            headers.Add(new HttpHeader("Host", ctx.Uri.Host));

            HttpRequest request = new HttpRequest();

            request.Method     = ctx.Verb;
            request.Uri        = ctx.Uri.PathAndQuery;
            request.Headers    = headers.ToArray();
            request.BodyStream = ctx.PayloadStream;

            HttpResponseStreamHandler responseHandler = new HttpResponseStreamHandler();

            responseHandler.IncomingHeaders += OnIncomingHeaders;
            responseHandler.IncomingBody    += OnIncomingBody;
            responseHandler.StreamComplete  += OnStreamComplete;

            return(connection.MakeRequest(request, responseHandler));
        }
Exemplo n.º 31
0
        private void OnHttpResponse(HttpClientConnection connection, byte[] data, int offset, int count)
        {
            try
            {
                connection.TimeoutTimer.Dispose();
                HttpListenerResponse response = connection.Context.Response;
                response.ContentType = "application/octet-stream";
                if (data[offset] == 0x1f && data[offset + 1] == 0x8b && data[offset + 2] == 0x08 && data[offset + 3] == 0x00)
                {
                    response.AddHeader("Content-Encoding", "gzip");
                }
                response.AddHeader("Access-Control-Allow-Origin", "*");
                response.ContentLength64 = count;
                Stream output = response.OutputStream;
                output.Write(data, offset, count);
                output.Close();
                connection.Close();
            }
            catch
            {

            }
        }
Exemplo n.º 32
0
        private void OnHttpRequest(IAsyncResult result)
        {
            try
            {
                HttpListener listener = (HttpListener)result.AsyncState;
                HttpListenerContext context = listener.EndGetContext(result);
                listener.BeginGetContext(OnHttpRequest, listener);
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;
                string sid = request.QueryString["sid"];
                GameSession session;
                if (string.IsNullOrEmpty(sid))
                {
                    session = GameSession.CreateNew(Guid.NewGuid(), request);
                }
                else
                {
                    session = GameSession.Get(sid) ?? GameSession.CreateNew(Guid.NewGuid(), request);
                }

                string data = "";
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    if (string.Compare(request.HttpMethod, "get", true) == 0)
                    {
                        data = request.RawUrl.Substring(8);
                        data = HttpUtility.UrlDecode(data);
                    }
                }
                else
                {
                    data = request.QueryString["d"];
                }

                if (string.IsNullOrEmpty(data))
                {
                    using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                    {
                        data = reader.ReadToEnd();
                        data = HttpUtility.ParseQueryString(data)["d"];
                    }
                }

                int statuscode = 0;
                Dictionary<string, string> param = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
                if (data != null)
                {
                    var nvc = HttpUtility.ParseQueryString(data);
                    foreach (var key in nvc.AllKeys)
                    {
                        param[key] = nvc[key];
                    }
                }
                statuscode = CheckHttpParam(param);

                if (statuscode != (int)HttpStatusCode.OK)
                {
                    response.StatusCode = statuscode;
                    response.Close();
                    return;
                }

                var httpresponse = new SocketGameResponse();
                httpresponse.WriteErrorCallback += new ActionDispatcher().ResponseError;

                HttpGet httpGet = new HttpGet(new RequestPackage() { UrlParam = data, Session = session });
                httpGet["UserHostAddress"] = session.EndAddress;
                httpGet["ssid"] = session.KeyCode.ToString("N");
                httpGet["http"] = "1";

                var clientConnection = new HttpClientConnection {
                    Context = context,
                    Session = session,
                    ActionGetter = httpGet,
                    GameResponse = httpresponse
                };
                clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, httpRequestTimeout, Timeout.Infinite);

                OnRequested(httpGet, httpresponse);
                byte[] respData = httpresponse.ReadByte();
                OnHttpResponse(clientConnection, respData, 0, respData.Length);

            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnHttpRequest error:{0}", ex);
            }
        }
Exemplo n.º 33
0
        private void OnHttpRequest(IAsyncResult result)
        {
            try
            {
                HttpListener listener = (HttpListener)result.AsyncState;
                HttpListenerContext context = listener.EndGetContext(result);
                listener.BeginGetContext(OnHttpRequest, listener);

                RequestPackage package;
                if (!ActionDispatcher.TryDecodePackage(context, out package))
                {
                    return;
                }

                GameSession session;
                if (package.ProxySid != Guid.Empty)
                {
                    session = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                    session.ProxySid = package.ProxySid;
                }
                else
                {
                    session = (string.IsNullOrEmpty(package.SessionId)
                            ? GameSession.GetSessionByCookie(context.Request)
                            : GameSession.Get(package.SessionId))
                        ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
                }
                package.Bind(session);

                ActionGetter httpGet = ActionDispatcher.GetActionGetter(package, session);
                if (package.IsUrlParam)
                {
                    httpGet["UserHostAddress"] = session.RemoteAddress;
                    httpGet["ssid"] = session.KeyCode.ToString("N");
                    httpGet["http"] = "1";
                }
                //set cookie
                var cookie = context.Request.Cookies["sid"];
                if (cookie == null)
                {
                    cookie = new Cookie("sid", session.SessionId);
                    cookie.Expires = DateTime.Now.AddMinutes(5);
                    context.Response.SetCookie(cookie);
                }


                var httpresponse = new SocketGameResponse();
                httpresponse.WriteErrorCallback += new ScutActionDispatcher().ResponseError;

                var clientConnection = new HttpClientConnection
                {
                    Context = context,
                    Session = session,
                    ActionGetter = httpGet,
                    GameResponse = httpresponse
                };
                var section = GetSection();
                clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, section.HttpRequestTimeout, Timeout.Infinite);
                byte[] respData = new byte[0];
                if (!string.IsNullOrEmpty(package.RouteName))
                {
                    if (CheckRemote(package.RouteName, httpGet))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(package.RouteName, httpGet, response);
                        respData = response.PopBuffer();
                    }
                }
                else
                {
                    DoAction(httpGet, httpresponse);
                    respData = httpresponse.ReadByte();
                }
                OnHttpResponse(clientConnection, respData, 0, respData.Length);

            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnHttpRequest error:{0}", ex);
            }
        }