Как запросить полную HTML-страницу с CSS и JS в C # HTTPListener - PullRequest
0 голосов
/ 15 октября 2019

Я хочу закодировать ac # Http webserver. Если запрашивается URL, я хочу отправить HTML-страницу с CSS и JS клиенту. Как я могу это сделать?

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();
            }
        }

Я хочу отправить клиенту полный веб-сайт HTML CSS JS.

извините за мой плохой английский.

Ответы [ 2 ]

0 голосов
/ 18 октября 2019

Как я только что понял, теперь я могу решить свою проблему.

Я поиграл с материалом Request URL / RawURL в классе HTTPListenerContext.

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();
        }
    }

Я просто отправляю толькофайлы, которые запрашивает клиент (пользователь). Благодаря моему хорошему веб-сайту HTML, он автоматически запрашивает файлы изображений, CSS и JSПоэтому, когда я перехожу на http://localhost:2002/, он автоматически отправляет мне полный веб-сайт.

извините за мой плохой английский

0 голосов
/ 15 октября 2019

Если упомянутый вами клиент способен использовать и оценивать JS и CSS, тогда вы можете просто включить javascript / CSS как встроенный или как отдельный файл в свой ответ, как показано ниже.

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>");

...