我正在学习HttpListener
。我正在使用HttpListener
创建一个小型应用程序,这是一个网络服务器
http://msdn.microsoft.com/en-us/library/system.net.httplistener%28v=vs.110%29.aspx和https://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server.aspx)。注意,没有ASP.NET的东西。
在我从_responderMethod
调用的函数中,我基本上返回HTML(从磁盘上的物理文件中读取),其中包含以下内容:
...
<link href="css/ui-lightness/jquery-ui-1.10.4.custom.css" rel="stylesheet">
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery-ui-1.10.4.custom.js"></script>
...
然而,正如预期的那样,似乎没有提供.css
和.js
文件(我可以说,因为在html之后,客户端上没有预期的样式或行为服务)。
如何提供此文件,我是否需要对HttpServerUtility.MapPath
执行某些操作?如果是的话,你能指点我的一些例子吗?
或者我是否需要扫描即将发布的HTML并打开(递归)读取并返回这些文件?我希望不会。
BTW,服务于此的C#代码如下所示,我的_responderMethod
只返回HTML文件的字符串,如上所述:
我按如下方式初始化并启动服务器:
WebServer ws = new WebServer(program.SendResponse, "http://<myip>:8080/");
ws.Run();
类构造函数非常多:
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
// A responder method is required
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) { }
.Run()
是:
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 { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
我的SendResponse()
:
public string SendResponse(HttpListenerRequest request)
{
return File.ReadAllText(@"static\index.html");
}
答案 0 :(得分:2)
如果您的HTML指定了您网站上的脚本或CSS文件,则客户端浏览器将请求它们。您的服务器也必须提供这些文件。脚本和CSS文件是您提供的文本文件,与提供HTML文件的方式非常相似,但您需要确保相应地更改内容类型标题。您以二进制格式提供二进制文件(图像等)。同样,您需要确保设置内容类型以指示它是图像。