C# HttpListener 在本机测试有用,在服务器上运行,客户端无法连接!

igufei 2016-05-29 10:35:29
C# HttpListener 在本机测试有用,在服务器上运行,客户端无法连接![图片说明](http://img.ask.csdn.net/upload/201605/29/1464531959_447895.png)

if (!HttpListener.IsSupported)
{
throw new System.InvalidOperationException(
"使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
}
// 注意前缀必须以 / 正斜杠结尾
string[] prefixes = new string[] { "http://localhost:49152/" };
// 创建监听器.
HttpListener listener = new HttpListener();
// 增加监听的前缀.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
// 开始监听
listener.Start();
Console.WriteLine("监听中...");
while (true)
{
// 注意: GetContext 方法将阻塞线程,直到请求到达
HttpListenerContext context = listener.GetContext();
// 取得请求对象
HttpListenerRequest request = context.Request;
Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes));
Console.WriteLine("Accept-Language: {0}",
string.Join(",", request.UserLanguages));
Console.WriteLine("User-Agent: {0}", request.UserAgent);
Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
Console.WriteLine("Connection: {0}",
request.KeepAlive ? "Keep-Alive" : "close");
Console.WriteLine("Host: {0}", request.UserHostName);
Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
// 取得回应对象
HttpListenerResponse response = context.Response;
// 构造回应内容
string responseString
= @"<html>
<head><title>From HttpListener Server</title></head>
<body><h1>Hello, world.</h1></body>
</html>";
// 设置回应头部内容,长度,编码
response.ContentLength64
= System.Text.Encoding.UTF8.GetByteCount(responseString);
response.ContentType = "text/html; charset=UTF-8";
// 输出回应内容
System.IO.Stream output = response.OutputStream;
System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
writer.Write(responseString);
// 必须关闭输出流
writer.Close();

if (Console.KeyAvailable)
break;
}
// 关闭服务器
listener.Stop();
...全文
470 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Justin-Liu 2016-05-30
  • 打赏
  • 举报
回复
网络是通的吗?
xuzuning 2016-05-30
  • 打赏
  • 举报
回复
string[] prefixes = new string[] { "http://localhost:49152/" }; 这是什么意思? localhost 是本机,你在服务器上也只监听本机?
乐百川 2016-05-30
  • 打赏
  • 举报
回复
是不是防火墙原因

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧