2013-10-09 5 views
0

그래서 웹 서버에 대한 또 다른 질문이 있습니다. 마지막 질문부터 몇 가지 새로운 기능을 추가했지만 이제는 또 다른 문제가 발생했습니다.C# Simple Web Server Image Read-In

서버가 HTML을 통해 호출되는 이미지를 제공 할 수있게하려고합니다. 그러나 이미지가 어떤 이유로 웹 페이지에 표시되지 않습니다. 나는 코드를 밟았으며 파일을 통해 전송하는 것처럼 보이지만 반대쪽에 표시되지 않습니다. 여기 내 코드 :

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) 
       { 

       } 
      } 
     } 
    } 
} 

미리 감사드립니다!

+0

문제를 조금 좁힐 수 있습니까? 이 서버의 실제 응답은 무엇입니까? 이미지를 게재 할 때 헤더와 콘텐츠는 무엇입니까? 그 catch 블록에서 catch되고 완전히 무시되는 오류가 있습니까? – David

답변

0

"image/gif"와 같이 HttpListenerResponse.ContentType을 이미지의 적절한 MIME 유형으로 설정해야합니다.

또한 예제 코드는 TextReader를 통해 이미지를 읽고이를 UTF8 바이트 배열로 변환합니다. 바이너리 파일에서는 작동하지 않습니다. 바이트를 조작합니다. FileStream 또는 이진 파일 내용을 수정하지 않고 반환하는 다른 방법으로 이러한 파일을 읽어야합니다.

+0

콘텐츠 유형을 정확히 얻으려면 어떻게해야합니까? –

+0

콘텐츠 형식은 파일 형식에 따라 다릅니다. 일반적으로 파일 확장자에서 추론 할 수 있습니다. 지금 가지고있는 하나의 케이스를 처리하고, 확장을보고, 그 확장을 볼 때 그 하나의 확장 (하드 코딩 됨)에 대한 적절한 ContentType을 반환하십시오. 일단 작동하면 질문은 마임 유형에 대한 확장 목록을 얻는 방법이됩니다. 이미 마임 유형에 대한 다른 좋은 대답이 있습니다. – huntharo

+0

이 작업을 시도했지만 다른쪽에 여전히 표시되지 않습니다. –