我有一個小型C#控制檯應用程序作爲Web服務器工作。它在NAT上與同一網絡中的設備反應良好,但是當我嘗試從外部IP訪問它時,我得到一個400.400在C#中使用簡單的網絡服務器的錯誤請求(無效主機)
路由器配置爲端口轉發,否則我得到404。
localhost:8888/test正常。 也192.168.0.x:8888 /測試任何設備。
xxx.xxx.xxx.xxx:8888/test因HTTP錯誤400失敗。請求主機名無效。
有什麼建議嗎?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace httpsrv
{
class Program
{
static void Main(string[] args)
{
WebServer ws = new WebServer(SendResponse, "http://localhost:8888/test/");
ws.Run();
Console.WriteLine("Pi server started");
Console.ReadKey();
ws.Stop();
}
public static string SendResponse(HttpListenerRequest request)
{
return string.Format("<HTML><BODY>Hosted from rasp. pi!<br>{0}</BODY></HTML>", DateTime.Now);
}
}
}
Web Server類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace httpsrv
{
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { }
finally
{
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { }
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}