How to request full HTML page with CSS and JS in C# HTTPListener

Viewed 1902

I want to code a c# Http webserver. If the URL is requested I want to send the HTML page with CSS and JS to the client. How can I do that?

static void Main(string[] args)
        {
            HttpListener server = new HttpListener();  // this is the http server
            //server.Prefixes.Add("http://127.0.0.1/");  //we set a listening address here (localhost)
            server.Prefixes.Add("http://localhost:2002/");

            server.Start();   // and start the server

            Console.WriteLine("Server started...");

            while (true)
            {
                HttpListenerContext context = server.GetContext();
                HttpListenerResponse response = context.Response;

                byte[] buffer = Encoding.UTF8.GetBytes("<html></html>");

                response.ContentLength64 = buffer.Length;
                Stream st = response.OutputStream;
                st.Write(buffer, 0, buffer.Length);

                context.Response.Close();
            }
        }

I want to send the full HTML CSS JS website to the client.

sry for my bad english.

2 Answers

As I just figured out, I can now fix my problem.

I played around with the Request URL / RawURL stuff in the HTTPListenerContext class.

static void Main(string[] args)
    {
        HttpListener server = new HttpListener();  // this is the http server
        //server.Prefixes.Add("http://127.0.0.1/");  //we set a listening address here (localhost)
        server.Prefixes.Add("http://localhost:2002/");

        server.Start();   // and start the server

        Console.WriteLine("Server started...");

        while (true)
        {
            HttpListenerContext context = server.GetContext();
            HttpListenerResponse response = context.Response;


            Console.WriteLine("URL: {0}", context.Request.Url.OriginalString);
            Console.WriteLine("Raw URL: {0}", context.Request.RawUrl);




            byte[] buffer = File.ReadAllBytes("." + context.Request.RawUrl.Replace("%20", " "));

            response.ContentLength64 = buffer.Length;
            Stream st = response.OutputStream;
            st.Write(buffer, 0, buffer.Length);

            context.Response.Close();
        }
    }

I simply send only the files the client (User) is requesting. Thanks to my good HTML website, it automatically requests the Pictures and CSS and JS files. So when I go onto http://localhost:2002/ it automatically sends me the full website.

sry for my bad english

If the client you mentioned is capable of consuming and evaluating JS and CSS then you can just include the javascript/CSS as inline or as a separate file as part of your response, as below..

byte[] buffer = Encoding.UTF8.GetBytes("<html>
<head>
    <title>Page title</title>
 <link rel='stylesheet' type='text/css' href='styles.css'> 
</head>
<body>
</body>
<script src='js/script.js'></script>
</html>");

Related