简体   繁体   English

C#简单Web服务器图像读入

[英]C# Simple Web Server Image Read-In

So I'm back with another question about my web server. 所以我回来了关于我的Web服务器的另一个问题。 I've added several new features to it since my last question, but now I've ran into another problem. 自上一个问题以来,我已经为其添加了一些新功能,但是现在我遇到了另一个问题。

I'm trying to allow the server to serve out an image that is called through HTML. 我试图允许服务器提供通过HTML调用的图像。 However, the image isn't displaying on the webpage for some reason. 但是,由于某种原因,该图像未显示在网页上。 I've stepped through the code and it does seem to be sending through the file, but it's just not displaying on the other end. 我已经遍历了代码,它似乎确实是通过文件发送的,但是它并没有显示在另一端。 Here is my code: 这是我的代码:

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;

namespace miniWebServer_csc360
{
    public partial class Form1 : Form
    {
        public static int requestCount = 0;
        public static Boolean singleUse = true;

        public static HttpListener listener = new HttpListener();

        //public static HttpListenerContext context;
        //public static HttpListenerResponse response;

        static Form1 thisform;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            thisform = this;
        }

        private void start_button_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(serverThread);
            t.Start();
        }

        public static void serverThread()
        {
            if (singleUse)
            {
                listener.Prefixes.Add("http://10.211.55.4:69/");
                listener.Prefixes.Add("http://localhost:69/");

                singleUse = false;
            }

            if (listener.IsListening)
                listener.Stop();

            else
                listener.Start();

            if (listener.IsListening)
            {
                thisform.Invoke((MethodInvoker)delegate { thisform.status_label.Text 
                   = "Listening..."; });
                thisform.Invoke((MethodInvoker)delegate { thisform.start_button.Text 
                   = "Stop Server"; });
            }

            else
            {
                thisform.Invoke((MethodInvoker)delegate { thisform.status_label.Text 
                   = "Not listening..."; });
                thisform.Invoke((MethodInvoker)delegate { thisform.start_button.Text 
                   = "Start Server"; });
            }

            while (listener.IsListening)
            {
                try
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerResponse response = context.Response;

                    requestCount++;

                    thisform.Invoke((MethodInvoker)delegate { thisform.counter.Text 
                       = requestCount.ToString(); });

                    string page = Directory.GetCurrentDirectory() 
                        + context.Request.Url.LocalPath;

                    if (context.Request.Url.LocalPath != "/HEAD.html" 
                         && context.Request.Url.LocalPath != "/favicon.ico")
                    {
                        if (context.Request.Url.LocalPath == "/")
                        {
                            string path = context.Request.Url.LocalPath + "index.html";
                                 thisform.Invoke((MethodInvoker)delegate
                            {
                                thisform.request_Box.AppendText(path + "\r\n");
                            });
                        }

                        else
                        {
                            thisform.Invoke((MethodInvoker)delegate
                            {
                                thisform.request_Box.AppendText
                                  (context.Request.Url.LocalPath + "\r\n");
                            });
                        }
                    }

                    if (context.Request.Url.LocalPath == "/")
                        page += "index.html";

                    TextReader tr = new StreamReader(page);
                    string msg = tr.ReadToEnd();

                    byte[] buffer = Encoding.UTF8.GetBytes(msg);

                    if (context.Request.Url.LocalPath == "/header.html")
                    {
                        File.WriteAllText(Directory.GetCurrentDirectory() + "/HEAD.html",
                            context.Request.HttpMethod + " " +
                            context.Request.RawUrl + " HTTP/" 
                            + context.Request.ProtocolVersion + "\n"
                            + context.Request.Headers.ToString());
                    }

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

                    context.Response.Close();
                }
                catch (Exception error)
                {

                }
            }
        }
    }
}

Thanks in advance! 提前致谢!

You have to set HttpListenerResponse.ContentType to the appropriate MIME type for the image, such as "image/gif". 您必须将HttpListenerResponse.ContentType设置为图像的适当MIME类型,例如“ image / gif”。

In addition, the example code is reading the image through a TextReader and converting it to a UTF8 byte array. 另外,示例代码是通过TextReader读取图像并将其转换为UTF8字节数组。 That's not going to work for binary files; 对于二进制文件,这是行不通的。 it'll mangle the bytes. 它会破坏字节。 You need to read those files with a FileStream or any other approach that will return the binary file contents unmodified. 您需要使用FileStream或任何其他方法读取这些文件,这些方法将返回未修改的二进制文件内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM