2013-09-30 35 views
4

我遇到了一個簡單的Web服務器,我正在寫一個問題。我需要能夠通過本地主機和IP連接到服務器。但是,我通過IP連接時遇到了問題。這裏是我的代碼:簡單的Web服務器:指定的網絡名稱格式無效

private void start_button_Click(object sender, EventArgs e) 
    { 
     start_button.Text = "Listening..."; 

     HttpListener server = new HttpListener(); 

     server.Prefixes.Add("http://201.0.0.10:69/"); 
     server.Prefixes.Add("http://localhost:69/"); 

     server.Start(); 

     while (true) 
     { 
      HttpListenerContext context = server.GetContext(); 
      HttpListenerResponse response = context.Response; 

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

      if (page == string.Empty) 
       page = page + "index.html"; 

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


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

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

      context.Response.Close(); 
     } 
    } 

我不斷收到此錯誤:指定網絡名稱的格式無效。

我知道我的問題就出在這一點:

server.Prefixes.Add("http://201.0.0.10:69/"); 

我可以通過本地主機連接,如果我註釋掉這一行。

有誰知道我可能做錯了什麼?


好,我知道了IP地址的工作,但現在我在這一行的一個問題:

if (page == string.Empty) 
      page = page + "index.html"; 

出於某種原因,它沒有增加的index.html到最後。

+1

發生此錯誤。你的機器實際上是否有'201.0.0.10'地址? –

+4

我的意思是:確保只使用分配給主機的實際IP地址。你可以使用'System.Net.Dns.GetHostEntry(「」)。AddressList'獲得它們。 –

+0

謝謝!這工作!我試圖使用我的公共IP而不是分配給我的電腦。現在我還有另一個問題。出於某種原因,將index.html添加到URL末尾的if語句不起作用。 –

回答

0

解決方案適用於我的是在applicationhost.config文件中添加綁定。

This answer給出了一個綁定信息位於何處以及如何手動編輯它的示例。

在你的情況,以下的綁定信息可能會解決你的問題:

<bindings> 
<binding protocol="http" bindingInformation="*:69:localhost" /> 
<binding protocol="http" bindingInformation="*:69:201.0.0.10" /> 
</bindings> 
0

除了在application.config文件中設置綁定你可能需要設置您的系統從某些IP地址,偵聽HTTP運行此命令:

netsh http add iplisten 201.0.0.10 

你也可能需要添加本地主機:

netsh http add iplisten 127.0.0.1 

而且在其他的答案中提到這些添加到綁定文件:如果您嘗試添加前綴不符合任何主機的地址

<binding protocol="http" bindingInformation="*:69:201.0.0.10" /> 
<binding protocol="http" bindingInformation="*:69:localhost" /> 
相關問題