コード例 #1
0
ファイル: ApiClient.cs プロジェクト: 0xdeafcafe/luno-dotnet
        protected ApiClient(ApiKeyConnection connection)
        {
            Ensure.ArgumentNotNull(connection, nameof(connection));

            ApiKeyConnection = connection;
            HttpConnection = new HttpConnection(ApiKeyConnection);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: ousttrue/ReactiveWeb
 IObservable<HttpConnection> GetConnection(Uri uri)
 {
     if(m_connection!= null 
         && m_connection.Uri.Host==uri.Host 
         && m_connection.Uri.Port==uri.Port
         && m_connection.IsConnected
         )
     {
         return Observable.Return(m_connection)
             .Do(x =>
             {
                 Console.WriteLine("<KeepAlive>");
             })
             ;
     }
     else
     {
         return HttpConnection.Create(uri).Connect()
             .Do(x => {
                 m_connection = x;
                 Console.WriteLine(x);
             })
             ;
     }
 }
コード例 #3
0
 public void SendMessageSendsAndReceivesAMessage()
 {
     var action = "DoSomething";
     var request = new ServerRequest
     {
         ServerName = "TestServer"
     };
     var url = "http://somewhere/";
     var factory = new TestClientFactory((u, a, d) =>
     {
         Assert.AreEqual(url + "server/TestServer/RawXmlMessage.aspx", u.AbsoluteUri);
         Assert.AreEqual("POST", a);
         Assert.AreEqual(action, d["action"]);
         Assert.AreEqual(request.ToString(), d["message"]);
         var theResponse = new Response
         {
             RequestIdentifier = request.Identifier
         };
         return Encoding.UTF8.GetBytes(theResponse.ToString());
     });
     var connection = new HttpConnection(new Uri(url), factory);
     var response = connection.SendMessage(action, request);
     Assert.IsInstanceOf<Response>(response);
     Assert.AreEqual(request.Identifier, response.RequestIdentifier);
 }
コード例 #4
0
 internal HttpListenerContext(HttpConnection cnc, ILogger logger)
 {
     this.cnc = cnc;
     _logger = logger;
     request = new HttpListenerRequest(this);
     response = new HttpListenerResponse(this, _logger);
 }
コード例 #5
0
ファイル: TestWebSeed.cs プロジェクト: Cyarix/monotorrent
        public void Setup()
        {
            requestedUrl.Clear();
            partialData = false;
            int i;
            for (i = 0; i < 1000; i++)
            {
                try
                {
                    listener = new HttpListener();
                    listener.Prefixes.Add(string.Format(listenerURL, i));
                    listener.Start();
                    break;
                }
                catch
                {

                }
            }
            listener.BeginGetContext(GotContext, null);
            rig = TestRig.CreateMultiFile();
            connection = new HttpConnection(new Uri(string.Format(listenerURL, i)));
            connection.Manager = rig.Manager;

            id = new PeerId(new Peer("this is my id", connection.Uri), rig.Manager);
            id.Connection = connection;
            id.IsChoking = false;
            id.AmInterested = true;
            id.BitField.SetAll(true);
            id.MaxPendingRequests = numberOfPieces;
            
            requests = rig.Manager.PieceManager.Picker.PickPiece(id, new List<PeerId>(), numberOfPieces);
        }
コード例 #6
0
		internal HttpListenerContext (HttpConnection cnc)
		{
			this.cnc   = cnc;
			err_status = 400;
			request    = new HttpListenerRequest (this);
			response   = new HttpListenerResponse (this);
		}
コード例 #7
0
ファイル: HttpServer.cs プロジェクト: jorgeantwan18/rokumedia
 public void RemoveConnection(HttpConnection connection)
 {
     lock (this._requests)
     {
         this._requests.Remove(connection);
     }
 }
コード例 #8
0
 public void ExecuteTest()
 {
     HttpConnection target = new HttpConnection();
     HttpWebRequest httpRequest = GetHttpWebRequest();
     string actual = target.Execute(payLoad, httpRequest);
     Assert.IsNotNull(actual);
 }
コード例 #9
0
ファイル: Client.cs プロジェクト: rtezli/consuldotnext
        public Client(HttpConnection connection)
        {
            _nodeName = Environment.GetEnvironmentVariable("CONSUL_CLIENT_NODE_NAME") ?? "undefined node";
            _serviceName = Environment.GetEnvironmentVariable("CONSUL_CLIENT_SERVICE_NAME") ?? "undefined service";
            _datacenterName = Environment.GetEnvironmentVariable("CONSUL_CLIENT_DATACENTER_NAME") ?? "dc1";

            _catalog = new Catalog(connection);
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: ousttrue/ReactiveWeb
 void Close()
 {
     if(m_connection!=null && m_connection.IsConnected)
     {
         (m_connection as IDisposable).Dispose();
         m_connection = null;
     }
 }
コード例 #11
0
//		private bool _headersSent;

		/// <summary>
		/// Initializes a new instance of the AspWorkerRequest class
		/// </summary>
		/// <param name="connection"></param>
		/// <param name="request"></param>
		public AspWorkerRequest(AspHost aspHost, HttpConnection connection, HttpRequest request) : base(string.Empty, string.Empty, null)
		{						
			_aspHost = aspHost;
			_connection = connection;
			_request = request;
			_response = new HttpResponse(new OkStatus());

			this.ParsePathInfo();
		}
コード例 #12
0
 public void Dispose()
 {
     lock (this)
     {
         if (_httpConnection != null)
         {
             _httpConnection.Dispose();
             _httpConnection = null;
         }
     }
 }
コード例 #13
0
		/// <summary>
		/// Initializes a new instance of the AddressBookItemConnectionManager class
		/// </summary>
		/// <param name="item">The address book item that defines the remote host to connect to</param>
		/// <param name="connection">The Tcp connection that will be used throughout the lifetime of the connection</param>
		public AddressBookItemConnectionManager(AddressBookItem item, HttpConnection connection)
		{
			if (item == null)
				throw new ArgumentNullException("item");

			if (connection == null)
				throw new ArgumentNullException("connection");

			_propertyBag = new Hashtable();
			_item = item;
			_connection = connection;
			_connection.Opened += new HttpConnectionEventHandler(OnInternalConnectionOpened);
			_connection.Closed += new HttpConnectionEventHandler(OnInternalConnectionClosed);
			_connection.Exception += new ExceptionEventHandler(OnInternalConnectionException);
		}      
コード例 #14
0
        public NanoHttpRequest(HttpConnection conn, string request)
        {
            Connection = conn;
            if (string.IsNullOrEmpty(request))
            {
                Invalid = true;
                return;
            }

            var fls = request.Split(new char[]{ ' ' }, 3);

            if (fls.Length < 2)
            {
                Invalid = true;
                return;
            }

            Method = fls[0];
            Address = fls[1];

            //if (Method == "POST")
            {
                var heco = request.Split(new string[]{ "\r\n\r\n" }, 2, StringSplitOptions.None);

                if (heco.Length < 2)
                {
                    Invalid = true;
                    return;
                }

                var he = heco[0];
                var co = heco[1];
                Content = co;
                var lines = he.Split(new string[]{ "\r\n", "\n" }, StringSplitOptions.None);

                for (int i = 1; i < lines.Length; i++)
                {
                    var hl = lines[i].Split(new String[]{": "}, 2, StringSplitOptions.None);
                    if (hl.Length < 2) continue;
                    Headers[hl[0]] = hl[1];
                }
            }
        }
コード例 #15
0
ファイル: HttpTransponder.cs プロジェクト: rongxiong/Scut
        public void RequestTimeout(HttpConnection connection)
        {
            var param = connection.Param;
            int msgId = param.Get("MsgId").ToInt();
            int actionId = param.Get("ActionId").ToInt();
            int errorCode = LanguageHelper.GetLang().ErrorCode;
            string errorMsg = LanguageHelper.GetLang().RequestTimeout;
            var head = new MessageHead(msgId, actionId, "st", errorCode, errorMsg);
            head.HasGzip = true;
            var ms = new MessageStructure();
            ms.WriteBuffer(head);
            byte[] data = ms.ReadBuffer();

            string remoteAddress = connection.Context.Request.RemoteEndPoint.Address.ToString();
            string successMsg = string.Format("{0}>>发送超时到{1} {2}字节!",
                                              DateTime.Now.ToString("HH:mm:ss:ms"), remoteAddress, data.Length);
            Console.WriteLine(successMsg);
            OnResponseCompleted(connection, data);
        }
コード例 #16
0
ファイル: NanoHttpServer.cs プロジェクト: Bit-notes/nanoboard
        private void Process(HttpConnection connection, NanoHttpRequest request)
        {
            if (request.Address == "/")
            {
                connection.Response(_root.Handle(request));
                return;
            }

            var endpoint = request.Address.Split(new char[]{'/'}, StringSplitOptions.RemoveEmptyEntries)[0];

            if (_handlers.ContainsKey(endpoint))
            {
                connection.Response(_handlers[endpoint].Handle(request));
            }

            else
            {
                connection.Response(new ErrorHandler(StatusCode.BadRequest, "Unknown endpoint: " + endpoint).Handle(request));
            }
        }
コード例 #17
0
ファイル: HttpServer.cs プロジェクト: jorgeantwan18/rokumedia
        protected override void Run()
        {
            this._listener.Start();
            while (true)
            {
                try
                {
                    TcpClient client = this._listener.AcceptTcpClient();
                    HttpConnection connection = new HttpConnection(this, client);
                    lock (this._requests)
                    {
                        this._requests.Add(connection);
                    }
                    connection.Start();

                }
                catch {
                
                }
            }
            
        }
コード例 #18
0
ファイル: HttpServer.cs プロジェクト: karliky/wowwow
        public virtual void OnAccept( IAsyncResult ar )
        {
            try
            {
                Socket newSocket = listenSocket.EndAccept( ar );

                if ( newSocket != null )
                {
                    HttpConnection newClient = new HttpConnection( newSocket, new RemoveClientDelegate( this.RemoveClient ) );
                    clients.Add( newClient );
                    newClient.Start();
                }
            }
            catch {}
            try
            {
                listenSocket.BeginAccept( new AsyncCallback( this.OnAccept ), listenSocket );
            }
            catch
            {
                Dispose();
            }
        }
コード例 #19
0
ファイル: HttpTransponder.cs プロジェクト: rongxiong/Scut
        public void Request(HttpConnection connection, string clientAddress, byte[] data)
        {
            string paramString = string.Empty;
            try
            {
                paramString = Encoding.ASCII.GetString(data);
                PacketMessage packet = ParsePacketMessage(clientAddress, paramString, ConnectType.Http);
                packet.Head.SSID = connection.SSID.ToString("N");
                HttpConnectionManager.Push(connection);

                if (ReceiveCompleted != null)
                {
                    //分发送到游戏服
                    byte[] packData = packet.ToByte();
                    string successMsg = string.Format("{0}>>{1}接收到{2}字节!",
                        DateTime.Now.ToString("HH:mm:ss:ms"), clientAddress, data.Length);
                    ReceiveCompleted.BeginInvoke(clientAddress, packData, OnReceiveCompleted, successMsg);
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Receive form http request:{0} error:{1}", paramString, ex);
            }
        }
コード例 #20
0
        internal HttpRequest(IPEndPoint client, string method, string path, string protocol, string version, NameValueCollection headers, byte[] postData, HttpConnection connection)
        {
            m_connection = connection;

            Client = client;
            Method = method;

            var pathDelim = path.IndexOf('?');
            if (pathDelim == -1)
            {
                Path = HttpUtility.UrlDecode(path);
                QueryString = new NameValueCollection();
            }
            else
            {
                Path = HttpUtility.UrlDecode(path.Substring(0, pathDelim));
                QueryString = HttpUtility.ParseQueryString(path.Substring(pathDelim + 1));
            }

            Protocol = protocol;
            Version = version;
            Headers = headers;
            PostData = postData;
        }
コード例 #21
0
 public HttpSecureConnectionState(HttpConnection connection, Action<HttpConnection> callback)
 {
     Connection = connection;
     Callback = callback;
 }
コード例 #22
0
        private void OnReceive(IAsyncResult ar)
        {
            _currentConnection = this;
            if (_idleTimer != null)
            {
                try
                {
                    _idleTimer.Change(_CONNECTION_IDLE_TIMEOUT, Timeout.Infinite);
                }
                catch (Exception e) { }
            }
            // been closed by our side.
            if (_inputStream == null)
                return;
            try
            {
                int bytesLeft = _inputStream.EndRead(ar);
                if (bytesLeft == 0)
                {
                    Logger.Trace("Client disconnected.");
                    if (_requests.Count > 0)
                    {
                        throw new ParserException("Failed to send complete request");
                    }
                    else
                    {
                        Close();
                        return;
                    }
                }

                Logger.Debug(Client.ToString() + " received " + bytesLeft + " bytes.");

                if (bytesLeft < 5000)
                {
                    string temp = Encoding.Default.GetString(_buffer, 0, bytesLeft);
                    Logger.Trace(temp);
                }

                int offset = _parser.Parse(_buffer,0,bytesLeft);
                bytesLeft -= offset;

                if (bytesLeft > 0)
                {
                    Logger.Trace("Moving " + bytesLeft + " from " + offset + " to beginning of array.");
                    Buffer.BlockCopy(_buffer, offset, _buffer, 0, bytesLeft);
                }
                try
                {
                    _inputStream.BeginRead(_buffer, 0, _buffer.Length - offset, OnReceive, null);
                }
                catch (Exception e)
                {
                    Close();
                }
            }
            catch (ParserException err)
            {
                Logger.Trace(err.ToString());
                SendBuffer(Encoding.Default.GetBytes("HTTP/1.0 " + ((int)HttpStatusCode.BadRequest).ToString() + " " + err.Message),false);
                Close();
            }
            catch (Exception err)
            {
                if (!(err is IOException))
                {
                    Logger.Error("Failed to read from stream: " + err);
                    SendBuffer(Encoding.Default.GetBytes("HTTP/1.0 " + ((int)HttpStatusCode.InternalServerError).ToString() + " " + err.Message),false);
                }
                Close();
            }
        }
コード例 #23
0
		/// <summary>
		/// Runs the background thread that listens for incoming connections
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnThreadRun(object sender, BackgroundThreadStartEventArgs e)
		{
			try
			{
				IPEndPoint ep = (IPEndPoint)e.Args[0];
            
				Debug.Assert(ep != null);
				Trace.WriteLineIf(_verbose, string.Format("Binding to the end point '{0}'.", ep.ToString()), TraceCategory);
                  
				_listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				_listeningSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
				_listeningSocket.Bind(ep);
            
				Trace.WriteLineIf(_verbose, string.Format("Listening for inbound connections on '{0}'.", ep.ToString()), TraceCategory);

				while(true)
				{           
					_listeningSocket.Listen(100); // pending connections queue length

					// accept the connection
					Socket socket = _listeningSocket.Accept();
      
					Trace.WriteLineIf(_verbose, string.Format("Accepted an inbound connection from '{0}'.", socket.RemoteEndPoint.ToString()), TraceCategory);

					// create a new connection for the connection
					HttpConnection connection = new HttpConnection(socket, _verbose);
					connection.RequestDispatcher = _dispatcher;
					connection.Exception += new EventHandler<ExceptionEventArgs>(this.OnConnectionException);
					connection.Opened += new EventHandler<HttpConnectionEventArgs>(this.OnConnectionOpened);
                    connection.Closed += new EventHandler<HttpConnectionEventArgs>(this.OnConnectionClosed); 
					connection.IsServerSideConnection = true;
					connection.BeginSession(true);                                       
				}  
			}
			catch(ThreadAbortException)
			{
			}
			catch(Exception ex)
			{
				this.OnException(this, new ExceptionEventArgs(ex));
			}
		}
コード例 #24
0
    private static void processAccepted (Socket socket, EndPointListener listener)
    {
      HttpConnection conn = null;
      try {
        conn = new HttpConnection (socket, listener);
        lock (listener._unregisteredSync)
          listener._unregistered[conn] = conn;

        conn.BeginReadRequest ();
      }
      catch {
        if (conn != null) {
          conn.Close (true);
          return;
        }

        socket.Close ();
      }
    }
コード例 #25
0
 internal void RemoveConnection (HttpConnection connection)
 {
   lock (_unregisteredSync)
     _unregistered.Remove (connection);
 }
コード例 #26
0
		/// <summary>
		/// Connects to the server specified by the endpoint, sends the request and waits for a response.
		/// </summary>
		/// <param name="ep">The address:port of the server</param>
		/// <param name="request">The request to send</param>
		/// <param name="exception">Any exception that is throw or encountered during the request/response session with the server</param>
		/// <param name="verbose">A flag that indicates the connection's verbosity level, true for more messages</param>
		/// <returns></returns>
		public static HttpResponse GetResponse(
			IPEndPoint ep,
			HttpRequest request, 
			out Exception exception, 
			bool verbose,
			EventHandler<HttpMessageProgressEventArgs> onSendProgress,
			EventHandler<HttpMessageProgressEventArgs> onRecvProgress,
			object stateObject)
		{
			#region Params Validation

			if (ep == null)
				throw new ArgumentNullException("ep");

			if (request == null)
				throw new ArgumentNullException("request");

			exception = null;

			#endregion

			// define a connection for this request/response session
			HttpConnection connection = null;

			try
			{
				// create a connection to the remote end point
				connection = new HttpConnection(ep, false, verbose, HttpOptions.SendTimeout, HttpOptions.RecvTimeout);
				
				// return a response from the server
				return HttpRequest.GetResponse(connection, request, out exception, onSendProgress, onRecvProgress, stateObject);
			}
            catch (ThreadAbortException)
            {
                
            }
			catch(Exception ex)
			{
                //Debug.WriteLine(ex);
				exception = ex;
			}
			finally
			{
				// always try and close the connect up afterwards
				if (connection != null)
					connection.Close();
			}
			return null;
		}
コード例 #27
0
		/// <summary>
		/// Sends the specified request and waits for a response using the specified connection.
		/// </summary>
		/// <param name="connection">The connection to use for communication</param>
		/// <param name="request">The request to send</param>
		/// <param name="exception">Any exception that is throw or encountered during the request/response session with the server</param>
		/// <returns></returns>
		public static HttpResponse GetResponse(
			HttpConnection connection, 
			HttpRequest request, 
			out Exception exception,
			EventHandler<HttpMessageProgressEventArgs> onSendProgress,
			EventHandler<HttpMessageProgressEventArgs> onRecvProgress,
			object stateObject)
		{
			#region Params Validation

			if (connection == null)
				throw new ArgumentNullException("connection");

			if (request == null)
				throw new ArgumentNullException("request");

			exception = null;

			#endregion

			// use the connection to get a response
			HttpResponse response = connection.GetResponse(request, onSendProgress, onRecvProgress, stateObject);

            exception = connection.GetLastException();

			// if there is no response, then obviously something went wrong, retrieve the last exception from the connection
			if (response == null)
			{
				if (exception != null)
					if (exception.GetType() == typeof(ThreadAbortException))
						throw exception;
			}
			
			// return the response
			return response;
		}
コード例 #28
0
        private string GenerateOAuthToken(string base64ClientID)
        {
            string response = null;

                Uri uniformResourceIdentifier = null;
                Uri baseUri = null;
                if (config.ContainsKey(BaseConstants.OAUTH_ENDPOINT))
                {
                    baseUri = new Uri(config[BaseConstants.OAUTH_ENDPOINT]);
                }
                else if (config.ContainsKey(BaseConstants.END_POINT_CONFIG))
                {
                    baseUri = new Uri(config[BaseConstants.END_POINT_CONFIG]);
                }
                bool success = Uri.TryCreate(baseUri, OAUTHTOKENPATH, out uniformResourceIdentifier);
                ConnectionManager connManager = ConnectionManager.Instance;
                HttpWebRequest httpRequest = connManager.GetConnection(ConfigManager.Instance.GetProperties(), uniformResourceIdentifier.AbsoluteUri);

                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", "Basic " + base64ClientID);
                string postRequest = "grant_type=client_credentials";
                httpRequest.Method = "POST";
                httpRequest.Accept = "*/*";
                httpRequest.UserAgent = RESTConfiguration.FormUserAgentHeader();
                foreach (KeyValuePair<string, string> header in headers)
                {
                    httpRequest.Headers.Add(header.Key, header.Value);
                }

                HttpConnection httpConnection = new HttpConnection(config);
                response = httpConnection.Execute(postRequest, httpRequest);
                JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
                string generatedToken = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];
                appID = (string)deserializedObject["app_id"];
                secondsToExpire = (int)deserializedObject["expires_in"];
                timeInMilliseconds = DateTime.Now.Millisecond;
                return generatedToken;
        }
コード例 #29
0
 internal static void SetCurrentConnection(HttpConnection con)
 {
     _currentConnection = con;
 }
コード例 #30
0
 private void _RequestLineRecieved(string[] words)
 {
     _idleTimer.Dispose();
     _idleTimer = new Timer(new TimerCallback(_IdleTimeout), null, _CONNECTION_IDLE_TIMEOUT, Timeout.Infinite);
     _currentConnection = this;
     if (words[0].ToUpper() != "HTTP"&&!_shutdown)
     {
         HttpRequest req = Requests.Dequeue();
         lock (_requests)
         {
             req.StartRequest(_rand.NextLong(), words, this, ref _parser);
             _requests.Add(req);
         }
     }
 }