我正在编写的简单网络服务器遇到问题。我需要能够通过 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/");
如果我注释掉这一行,我可以通过本地主机连接。
有谁知道我可能做错了什么?
好的,我的 IP 地址可以正常工作,但现在我遇到了这一行的问题:
if (page == string.Empty)
page = page + "index.html";
由于某种原因,它没有将index.html 添加到末尾。
以及在中设置绑定application.config
文件中,您可能需要通过运行以下命令将系统设置为侦听来自某些 IP 地址的 http:
netsh http add iplisten 201.0.0.10
您可能还需要添加 localhost:
netsh http add iplisten 127.0.0.1
正如其他答案中提到的,将这些添加到绑定文件中:
<binding protocol="http" bindingInformation="*:69:201.0.0.10" />
<binding protocol="http" bindingInformation="*:69:localhost" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)