Beispiel #1
0
 private static void WriteRequest(HTTPRequestBuilder Request)
 {
     Console.ForegroundColor = ConsoleColor.Green;
     Console.WriteLine("Request:");
     Console.ForegroundColor = ConsoleColor.Gray;
     Console.WriteLine(Request.EntireRequestHeader + Environment.NewLine);
 }
Beispiel #2
0
        /// <summary>
        /// Main.
        /// </summary>
        /// <param name="myArgs">The arguments.</param>
        public static void Main(String[] myArgs)
        {
            #region Start TCPServers

            //var _TCPServer1 = new TCPServer(new IPv4Address(new Byte[] { 192, 168, 178, 31 }), new IPPort(2001), NewConnection =>
            //                                   {
            //                                       NewConnection.WriteToResponseStream("Hello world!" + Environment.NewLine + Environment.NewLine);
            //                                       NewConnection.Close();
            //                                   }, true);

            //Console.WriteLine(_TCPServer1);

            // The first line of the repose will be served from the CustomTCPConnection handler.
            var _TCPServer2 = new TCPServer<CustomTCPConnection>(IPv4Address.Any, new IPPort(2002), NewConnection =>
                                               {
                                                   NewConnection.WriteToResponseStream("...world!" + Environment.NewLine + Environment.NewLine);
                                                   NewConnection.Close();
                                               }, true);

            Console.WriteLine(_TCPServer2);

            #endregion

            #region Start HTTPServers

            // Although the socket listens on IPv4Address.Any the service is
            // configured to serve clients only on http://localhost:8181
            // More details within DefaultHTTPService.cs
            var _HTTPServer1 = new HTTPServer(IPv4Address.Any, new IPPort(8181), Autostart: true)
                                   {
                                       ServerName = "Default Hermod Demo"
                                   };

            Console.WriteLine(_HTTPServer1);

            // This service uses a custom HTTPService defined within IRESTService.cs
            var _HTTPServer2 = new HTTPServer<IRESTService>(IPv4Address.Any, IPPort.HTTP, Autostart: true)
                                   {
                                       ServerName = "Customized Hermod Demo"
                                   };

            Console.WriteLine(_HTTPServer2);

            #endregion

            #region UDP Servers

            var _UDPServer1 = new UDPServer(new IPPort(5555), NewPacket =>
            {
                //NewPacket.Data = new Byte[10];
             //   NewPacket.Close();
            }, true);

            #endregion

            var _client1     = new HTTPClient(IPv4Address.Localhost, IPPort.HTTP);

            var _request0    = _client1.GET("/HelloWorld").
                                        SetHost("localhorst").
                                        AddAccept(HTTPContentType.TEXT_UTF8, 1);

            var _request1    = _client1.GET("/HelloWorld").
                                        SetHost("localhorst").
                                        AddAccept(HTTPContentType.HTML_UTF8, 1);

            //WriteRequest(_request0.EntireRequestHeader);

            //_client1.Execute(_request0, response => WriteResponse(response.Content.ToUTF8String())).
            //         ContinueWith(HTTPClient => { WriteRequest(_request1.EntireRequestHeader); return HTTPClient.Result; }).
            //         ContinueWith(HTTPClient => HTTPClient.Result.Execute(_request1, response => WriteResponse(response.Content.ToUTF8String()))).
            //         Wait();

            var _client2 = new HTTPClient(IPv4Address.Parse("188.40.47.229"), IPPort.HTTP);
            var _requestA = _client2.GET("/").
                                     SetProtocolVersion(HTTPVersion.HTTP_1_1).
                                     SetHost("www.ahzf.de").
                                     SetUserAgent("Hermod HTTP Client v0.1").
                                     SetConnection("keep-alive").
                                     AddAccept(HTTPContentType.HTML_UTF8, 1);

            var _requestB = _client2.GET("/nfgj").
                                     SetProtocolVersion(HTTPVersion.HTTP_1_1).
                                     SetHost("www.ahzf.de").
                                     SetUserAgent("Hermod HTTP Client v0.1").
                                     SetConnection("keep-alive").
                                     AddAccept(HTTPContentType.HTML_UTF8, 1);

            WriteRequest(_requestA);
            _client2.Execute(_requestA, response => WriteResponse(response)).
                     ContinueWith(Client => Client.Result.Execute(_requestB, response => WriteResponse(response)));

            var _req23a = new HTTPRequestBuilder().
                              SetHTTPMethod      (HTTPMethod.GET).
                              SetProtocolName    ("µHTTP").
                              SetProtocolVersion (new HTTPVersion(2, 0)).
                              SetHost            ("localhorst").
                              SetUserAgent       ("Hermod µHTTP Client").
                              SetContent         ("This the HTTP content...");

            _req23a.QueryString.Add("name",   "alice").
                                Add("friend", "bob").
                                Add("friend", "carol");

            var _req23b = new HTTPRequestBuilder() {
                              HTTPMethod        = HTTPMethod.GET,
                              ProtocolName      = "µHTTP",
                              ProtocolVersion   = new HTTPVersion(2, 0),
                              Host              = "localhorst",
                              UserAgent         = "Hermod µHTTP Client",
                              Content           = "This the HTTP content...".ToUTF8Bytes()
                          };

            //            var Response = new TCPClientRequest("localhost", 80).Send("GETTT / HTTP/1.1").FinishCurrentRequest().Response;

            Console.ReadLine();
            Console.WriteLine("done!");
        }
Beispiel #3
0
        public Task<HTTPClient> Execute(HTTPRequestBuilder HTTPRequest, Action<HTTPResponse> HTTPResponseDelegate)
        {
            return Task<HTTPClient>.Factory.StartNew(() =>
            {

                #region Data

                Boolean _EndOfHTTPHeader    = false;
                long    _Length             = 0;
                long    EndOfHeaderPosition = 6;

                #endregion

                #region Client initialisieren und mit dem Server verbinden

                // Init TcpClient
                if (TCPClient == null)
                    TCPClient = new TcpClient(this.RemoteIPAddress.ToString(), this.RemotePort.ToInt32());
                    //TCPClient.ReceiveTimeout = 5000;

                // Open stream for reading and writting
                if (TCPStream == null)
                    TCPStream = TCPClient.GetStream();

                #endregion

                #region Send Request

                var _RequestBytes = (HTTPRequest.EntireRequestHeader + Environment.NewLine + Environment.NewLine).ToUTF8Bytes();
                TCPStream.Write(_RequestBytes, 0, _RequestBytes.Length);

                var _MemoryStream = new MemoryStream();
                var _Buffer       = new Byte[65535];
                var sw            = new Stopwatch();

                #endregion

                #region Wait for the server to react!

                sw.Start();

                while (!TCPStream.DataAvailable || sw.ElapsedMilliseconds > 20000)
                    Thread.Sleep(1);

                if (!TCPStream.DataAvailable && sw.ElapsedMilliseconds > 20000)
                {
                    TCPClient.Close();
                    throw new ApplicationException("Could not read from the TCP stream!");
                }

                sw.Stop();

                #endregion

                #region Read

                TCPStream.ReadTimeout = 2;

                while (!_EndOfHTTPHeader || TCPStream.DataAvailable || !TCPClient.Connected)
                {

                    #region Read the entire stream into the memory <= Rethink this someday!

                    while (TCPStream.DataAvailable)
                        _MemoryStream.Write(_Buffer, 0, TCPStream.Read(_Buffer, 0, _Buffer.Length));

                    #endregion

                    #region Walk through the stream and search for two consecutive newlines indicating the end of the HTTP header

                    _Length = _MemoryStream.Length;

                    if (_Length > 4)
                    {

                        _MemoryStream.Seek(0, SeekOrigin.Begin);

                        int state = 0;
                        int _int  = 0;
                        _EndOfHTTPHeader = false;

                        while (!_EndOfHTTPHeader || _int == -1)
                        {

                            _int = _MemoryStream.ReadByte();

                            switch (state)
                            {
                                case 0 : if (_int == 0x0d) state = 1; else state = 0; break;
                                case 1 : if (_int == 0x0a) state = 2; else state = 0; break;
                                case 2 : if (_int == 0x0d) state = 3; else state = 0; break;
                                case 3 : if (_int == 0x0a) _EndOfHTTPHeader = true; else state = 0; break;
                                default : state = 0; break;
                            }

                        }

                        if (_EndOfHTTPHeader)
                            break;

                    }

                    #endregion

                }

                if (_EndOfHTTPHeader == false)
                    throw new ApplicationException("Could not find the end of the HTTP protocol header!");

                EndOfHeaderPosition = _MemoryStream.Position - 3;

                #endregion

                #region Copy HTTP header data

                var HeaderBytes = new Byte[EndOfHeaderPosition - 1];
                _MemoryStream.Seek(0, SeekOrigin.Begin);
                _MemoryStream.Read(HeaderBytes, 0, HeaderBytes.Length);

                #endregion

                var _HTTPResponse = new HTTPResponse(HeaderBytes.ToUTF8String());

                #region Read 'Content-Length' bytes...

                // Copy only the number of bytes given within
                // the HTTP header element 'Content-Length'!
                if (_HTTPResponse.ContentLength.HasValue)
                {

                    _MemoryStream.Seek(4, SeekOrigin.Current);
                    var _Read        = _MemoryStream.Read(_Buffer, 0, _Buffer.Length);
                    var _StillToRead = (Int32) _HTTPResponse.ContentLength.Value - _Read;
                    _HTTPResponse.ContentStream.Write(_Buffer, 0, _Read);
                    var _CurrentBufferSize = 0;

                    var Retries = 0;

                    while (Retries < 10)
                    {

                        while (TCPStream.DataAvailable)
                        {
                            _CurrentBufferSize = Math.Min(_Buffer.Length, (Int32) _StillToRead);
                            _Read              = TCPStream.Read(_Buffer, 0, _CurrentBufferSize);
                            _HTTPResponse.ContentStream.Write(_Buffer, 0, _Read);
                            _StillToRead -= _Read;
                            Retries = 0;
                        }

                        if (_StillToRead <= 0)
                            break;

                        Thread.Sleep(10);
                        Retries++;

                    }

                    _HTTPResponse.ContentStreamToArray();

                }

                #endregion

                #region ...or read till timeout!

                else
                {

                    _MemoryStream.Seek(4, SeekOrigin.Current);
                    _HTTPResponse.ContentStream.Write(_Buffer, 0, _MemoryStream.Read(_Buffer, 0, _Buffer.Length));

                    var Retries = 0;

                    while (Retries < 10)
                    {

                        while (TCPStream.DataAvailable)
                        {
                            _HTTPResponse.ContentStream.Write(_Buffer, 0, TCPStream.Read(_Buffer, 0, _Buffer.Length));
                            Retries = 0;
                        }

                        Thread.Sleep(10);
                        Retries++;

                    }

                    _HTTPResponse.ContentStreamToArray();

                }

                #endregion

                #region Close connection if requested!

                if (_HTTPResponse.Connection == "close")
                {
                    TCPClient.Close();
                    TCPClient = null;
                    TCPStream = null;
                }

                #endregion

                #region Call HTTPResponse delegates

                if (HTTPResponseDelegate != null)
                    HTTPResponseDelegate(_HTTPResponse);

                #endregion

                return this;

            }, TaskCreationOptions.AttachedToParent);
        }