C# HttpListener赢得';即使允许使用防火墙,也不能在网络上工作
我正在使用以下代码添加http侦听器:C# HttpListener赢得';即使允许使用防火墙,也不能在网络上工作,c#,networking,webserver,firewall,httplistener,C#,Networking,Webserver,Firewall,Httplistener,我正在使用以下代码添加http侦听器: 公共类Web服务器 { 私有只读HttpListener _listener=new HttpListener(); 私有只读函数响应方法; 公共Web服务器(字符串[]前缀,Func方法) { 如果(!HttpListener.IsSupported) 抛出新的NotSupportedException( “需要Windows XP SP2、Server 2003或更高版本。”); //例如,URI前缀是必需的 // "http://localhost:
公共类Web服务器
{
私有只读HttpListener _listener=new HttpListener();
私有只读函数响应方法;
公共Web服务器(字符串[]前缀,Func方法)
{
如果(!HttpListener.IsSupported)
抛出新的NotSupportedException(
“需要Windows XP SP2、Server 2003或更高版本。”);
//例如,URI前缀是必需的
// "http://localhost:8080/index/".
if(前缀==null | |前缀.长度==0)
抛出新的ArgumentException(“前缀”);
//需要响应者方法
if(方法==null)
抛出新的ArgumentException(“方法”);
foreach(前缀中的字符串s)
_listener.Prefixes.Add(s);
_responderMethod=方法;
_listener.Start();
}
公共Web服务器(Func方法,参数字符串[]前缀)
:this(前缀、方法){}
公开募捐
{
ThreadPool.QueueUserWorkItem((o)=>
{
//WriteLine(“正在运行的Web服务器…”);
尝试
{
while(_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c)=>
{
var ctx=c作为HttpListenerContext;
尝试
{
字符串rstr=\u responderMethod(ctx.Request,ctx.Response);
字节[]buf=Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64=基本长度;
ctx.Response.OutputStream.Write(buf,0,buf.Length);
}
catch{}//禁止任何异常
最后
{
//始终关闭小溪
ctx.Response.OutputStream.Close();
}
},_listener.GetContext());
}
}
catch{}//禁止任何异常
});
}
公共停车场()
{
_listener.Stop();
_listener.Close();
}
}
静态类程序
{
公共const int PORT=18991;
[状态线程]
静态void Main()
{
WebServer ws=新的WebServer(SendResponse,“http://+:“+PORT+”/”;
ws.Run();
Application.Run(新Form1());
ws?.Stop();
}
私有静态字符串SendResponse(HttpListenerRequest请求,HttpListenerResponse响应)
{
返回“ok”;
}
}
这在本地机器上运行良好,但是它不会侦听来自网络内其他设备的请求。我甚至向防火墙添加了一个允许连接的传出传入规则,我使用netsh http add urlacl URL=“http://+:18991/”user=everybody
添加了URL,并以管理员权限启动了应用程序,但没有成功
如何允许局域网内的远程设备发出请求?以下是您可以尝试的步骤,看看它们是否有帮助:
HttpListener
:ipconfig
并检查您的IP地址:
我甚至在防火墙中添加了一条传出规则
。你不认为这应该是一条新规则吗…@Eser对不起,我错了。我的意思是,我向防火墙添加了一个传入规则。但是它不会侦听来自网络内其他设备的请求。
您(在服务器端和客户端)遇到了什么错误?@Eser没有错误,只是请求设备超时,应用程序中没有错误。您可以ping服务器吗?您是否可以连接到服务器端口(例如使用telnet)?
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace HttpTestServer
{
public class MainWindow
{
private readonly HttpListener _httpListener;
public MainWindow()
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add("http://*:9191/");
Task.Run(Start);
}
public async Task Start()
{
_httpListener.Start();
while (true)
{
var context = await _httpListener.GetContextAsync();
using (var sw = new StreamWriter(context.Response.OutputStream))
{
await sw.FlushAsync();
}
}
}
}
}