HttpListener implements small web servers

Time:2019-10-23

HttpListener implements web servers

For small servers, simple, convenient, no deployment required.

The total amount of code is no more than 50 lines.

static void Main(string[] args)
        {
            // create HTTP listener
            using (var httpListener = new HttpListener())
            {
                // listening path
                httpListener.Prefixes.Add("http://localhost:8820/");
                // set anonymous access
                httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                // start listening
                httpListener.Start();
                Console.WriteLine(" listener port :8820... ");
                while (true)
                {
                    Wait for the incoming request to be received and return, which blocks the thread until the request arrives
                    var context = httpListener.GetContext();
                    // gets the requested object
                    HttpListenerRequest request = context.Request;
                    Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
                    var reader = new StreamReader(request.InputStream);
                    Var MSG = reader. ReadToEnd (); // read incoming information

                    //Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes));
                    //Console.WriteLine("Accept-Language: {0}",
                    //    string.Join(",", request.UserLanguages));
                    Console.WriteLine("User-Agent: {0}", request.UserAgent);
                    Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
                    Console.WriteLine("Connection: {0}",
                        request.KeepAlive ? "Keep-Alive" : "close");
                    Console.WriteLine("Host: {0}", request.UserHostName);
                    Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);

                    // get the response object
                    HttpListenerResponse response = context.Response;

                    // set response header content, length, code
                    response.ContentEncoding = Encoding.UTF8;
                    //response.ContentType = "text/plain;charset=utf-8";
                    
                    //var path = @"C:\Users\wyl\Desktop\cese\";
                    /// access file name
                    //var fileName = request.Url.LocalPath;

                    // read the contents of the file
                    //var buff = File.ReadAllBytes(path + fileName);
                    //response.ContentLength64 = buff.Length;

                    //-------------------------
                    //byte[] data = new byte[1] { 1 };
                    //StringWriter sw = new StringWriter();
                    //XmlSerializer xm = new XmlSerializer(data.GetType());
                    //xm.Serialize(sw, data);
                    //var buff = Encoding.UTF8.GetBytes(sw.ToString());
                    //------------------------

                    //-------------------------------
                    // construct the soap request information
                    //response.ContentType = "text/xml; charset=utf-8";
                    //StringBuilder soap = new StringBuilder();
                    //soap.Append("");
                    //soap.Append("");
                    //soap.Append("");
                    //soap.Append("");
                    //soap.Append("183.39.119.90");
                    //soap.Append("");
                    //soap.Append("");
                    //soap.Append("");
                    //byte[] buff = Encoding.UTF8.GetBytes(soap.ToString());
                    //-----------------------------------

                    response.ContentType = "text/xml; charset=utf-8";
                    string responseString = string.Format(" {0}", DateTime.Now);
                    byte[] buff = Encoding.UTF8.GetBytes(responseString);

                    // output response content
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buff, 0, buff.Length);
                    // the output stream must be closed
                    output.Close();
                }
            }
        }

 

Can be accessed directly through the web page.

Program access method

string httpUrl = System.Configuration.ConfigurationManager.AppSettings["url"];// http://localhost:8820/
            WebRequest webRequest = WebRequest.Create(httpUrl);
            webRequest.ContentType = "text/xml; charset=utf-8";
            webRequest.Method = "POST";
            string responseString = string.Format(" {0}", DateTime.Now);
            //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                byte[] paramBytes = Encoding.UTF8.GetBytes(responseString);
                requestStream.Write(paramBytes, 0, paramBytes.Length);
            }

            // response
            WebResponse webResponse = webRequest.GetResponse();
            using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
            {
                string result = "";
                result = myStreamReader.ReadToEnd();
            }

JSON data transfer method

//data no data object
string str = JsonConvert.SerializeObject(data);
string res = Post(httpUrl, str);



 public static string Post(string url, string json)
        {
            string st;
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // create the request
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                Request. The Method = "POST"; // request by post
                request.AllowAutoRedirect = true;
                request.MaximumResponseHeadersLength = 1024;
                request.ContentType = "application/json";
                //request.ContentType = "text/xml; charset=utf-8";
                byte[] jsonbyte = Encoding.UTF8.GetBytes(json);
                Stream postStream = request.GetRequestStream();
                postStream.Write(jsonbyte, 0, jsonbyte.Length);
                postStream.Close();
                // send the request and get the corresponding response data    
                HttpWebResponse res = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                st = sr.ReadToEnd();
            }
            catch (WebException ex)
            {
                //Log4netHelper.WriteErrorLog(url, ex);
                st = null;
            }

            return st;
        }