igufei 2016-05-29 14:42 采纳率: 100%
浏览 2611
已采纳

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

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

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
= @"

From HttpListener Server

Hello, world.


";
// 设置回应头部内容,长度,编码
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();
  • 写回答

3条回答 默认 最新

  • lhl_lqc 2016-06-01 02:28
    关注

    如果需要公网访问,则防火墙要关闭,并且监听端口要打开。不过一般不建议开启非通用端口,可以在80或者443上监听。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配