Web server HttpListener response

user3137034 picture user3137034 · Dec 26, 2013 · Viewed 15.5k times · Source

I have some problems with displaying HttpListenerResponse in correct way. I am using http://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server.aspx as a sample! I want to display "1.html" but I can not!When I display it in my browser it display well. When I try to display as a response it displays with out image girl.png

code of "1.html"

    <HTML>
        <BODY>
            My web page.<br> 
            <p>
              <img src="girl.png" width="189" height="255" alt="lorem">
              <input id="btnLogin" type="button" value="login"  " style="width:100px;" />
            </p>
        </BODY>
    </HTML>

WebServer.cs

using System;
using System.Net;
using System.Threading;
using System.Linq;
using System.Text;
using System.IO;

namespace SimpleWebServer
{
    public class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, string> _responderMethod;

        public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
        {
            if (!HttpListener.IsSupported)
                throw new NotSupportedException(
                    "Needs Windows XP SP2, Server 2003 or later.");

            // URI prefixes are required, for example 
            // "http://localhost:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");

            // A responder method is required
            if (method == null)
                throw new ArgumentException("method");

            foreach (string s in prefixes)
                _listener.Prefixes.Add(s);

            _responderMethod = method;
            _listener.Start();
            _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener);
        }
        private static void ListenerCallback(IAsyncResult result)
        {
            HttpListener listener = (HttpListener)result.AsyncState;
            listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
            Console.WriteLine("New request.");

            HttpListenerContext context = listener.EndGetContext(result);
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;


            byte[] page = GetFile("1.html");

            response.ContentLength64 = page.Length;
            Stream output = response.OutputStream;
            output.Write(page, 0, page.Length);
            output.Close();


        }
        public static byte[] GetFile(string file)
        {
            if (!File.Exists(file)) return null;
            FileStream readIn = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[1024 * 1000];
            int nRead = readIn.Read(buffer, 0, 10240);
            int total = 0;
            while (nRead > 0)
            {
                total += nRead;
                nRead = readIn.Read(buffer, total, 10240);
            }
            readIn.Close();
            byte[] maxresponse_complete = new byte[total];
            System.Buffer.BlockCopy(buffer, 0, maxresponse_complete, 0, total);
            return maxresponse_complete;
        }

        public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
            : this(prefixes, method) { }

        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Console.WriteLine("Webserver running...");
                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                string rstr = _responderMethod(ctx.Request);
                                byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                            }
                            catch { } // suppress any exceptions
                            finally
                            {
                                // always close the stream
                                ctx.Response.OutputStream.Close();
                            }
                        }, _listener.GetContext());
                    }
                }
                catch { } // suppress any exceptions
            });
        }
            public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }
    }    }

Code in main Form

private void Form1_Load(object sender, EventArgs e)
        {
            WebServer ws = new WebServer(SendResponse, "http://localhost:8080/test/");
            ws.Run();
            Console.WriteLine("A simple webserver. Press a key to quit.");
            Console.ReadKey();
            ws.Stop();
        }
        public static string SendResponse(HttpListenerRequest request)
        {
            return string.Format("<HTML><BODY>My web page.<br>{0}   <p><input type='submit' value='Отправить'></BODY></HTML>", DateTime.Now);            }

How display my 1.html as in browser?

Answer

FoxHound picture FoxHound · Dec 26, 2013

When I look at your code, the first thing I see is that your image is referenced with a relative path. If you stream the HTML code to another server, it cannot find the image if it isn't there on the other end in that relative location.

Use a full URL reference (e.g. http://otherserver.com/girl.png) to the image and it should be accessible.