【发布时间】:2013-10-06 09:47:10
【问题描述】:
我在编写一个简单的 Web 服务器时遇到问题。我需要能够通过 localhost 和 IP 连接到服务器。但是,我在通过 IP 连接时遇到问题。这是我的代码:
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/");
如果我注释掉这一行,我可以通过 localhost 连接。
有人知道我做错了什么吗?
好的,我得到了 IP 地址,但现在我遇到了这行的问题:
if (page == string.Empty)
page = page + "index.html";
由于某种原因,它没有将 index.html 添加到末尾。
【问题讨论】:
-
如果您尝试添加与您的任何主机地址都不对应的前缀,则会发生此错误。你的机器真的有
201.0.0.10地址吗? -
我的意思是:确保只使用分配给主机的实际 IP 地址。您可以使用
System.Net.Dns.GetHostEntry("").AddressList获取它们。 -
谢谢!那行得通!我试图使用我的公共 IP 而不是分配给我的计算机的一个。现在我遇到了另一个问题。出于某种原因,将 index.html 添加到 URL 末尾的 if 语句不起作用。
-
就在
if之前,您将page设置为CurentDirectory+LocalPath。你怎么期望它是空的?您可以将其更改为if (context.Request.Url.LocalPath == "/")之类的内容(如果未输入路径,浏览器会添加正斜杠)。
标签: c# httplistener