【问题标题】:Web server HttpListener responseWeb 服务器 HttpListener 响应
【发布时间】:2013-12-26 15:16:43
【问题描述】:

我在以正确方式显示 HttpListenerResponse 时遇到了一些问题。 我使用http://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server.aspx 作为样本!我想显示“1.html”,但我不能!当我在浏览器中显示它时,它显示得很好。当我尝试显示为响应时,它显示没有图像 girl.png

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

主窗体中的代码

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

如何在浏览器中显示我的 1.html?

【问题讨论】:

  • 尽量不要抑制异常。如果出了什么问题,您将不知道是什么。

标签: c# http webserver httplistenerrequest


【解决方案1】:

当我查看您的代码时,我首先看到的是您的图像是通过相对路径引用的。 如果您将 HTML 代码流式传输到另一台服务器,如果该相对位置的另一端不存在该图像,它将无法找到该图像。

对图片使用完整的 URL 引用(例如http://otherserver.com/girl.png),它应该可以访问。

【讨论】:

  • 对不起,猎狐犬错了!客户端连接到 Web 服务器并作为响应服务器向客户端发送 html 页面!
  • 通常 HTML 文件只是文本,图像不是页面本身的一部分。图像只是从外部检索并显示在页面中的东西。引起我注意的其他内容:您的 SendResponse 函数返回一个固定字符串,该字符串与您的文件几乎相同,但减去了图像标签。
  • 我已将您的代码放在一个小型测试应用程序中,但似乎返回到浏览器的 html 只是找不到图像。您拥有的 Web 服务器非常基本,它只返回 html 页面,仅此而已,然后由浏览器解释。由于浏览器从不接收任何图像数据,也无法在其工作文件夹中找到它,因此无法在适当位置显示图像并显示“Lorem”。顺便说一句,您应该添加“response.ContentType = “text/html”;”到您的 ListenerCallback 函数,以便您的浏览器知道它正在接收的 html
猜你喜欢
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 2017-08-23
  • 2011-11-18
  • 1970-01-01
相关资源
最近更新 更多