[英]Get web traffic on port using http listener
我已经使用http侦听器设置了一个Web服务器。 它用于显示html文件。 html文件创建了一个我希望应用程序获取的请求。 以下是fiddler中请求的屏幕截图: 这是唯一需要捕获的请求
这是我试过的:
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
Console.Write(ctx.Response.OutputStream);
每次在服务器上发出请求时,此代码始终返回“System.Net.HttpResponseStream”。 我想看看它返回的是什么,但是作为一个字符串。
这是我的网络服务器代码:
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(IReadOnlyCollection<string> prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
{
throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
}
// URI prefixes are required eg: "http://localhost:8080/test/"
if (prefixes == null || prefixes.Count == 0)
{
throw new ArgumentException("URI prefixes are required");
}
if (method == null)
{
throw new ArgumentException("responder method required");
}
foreach (var 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
{
if (ctx == null)
{
return;
}
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch
{
// ignored
}
finally
{
// always close the stream
if (ctx != null)
{
ctx.Response.OutputStream.Close();
}
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
// ignored
}
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}
从您提供的代码看起来您将rstr
作为UTF8字符串写入输出流,因此当您再次读取输出流以获得返回的内容时,您将获得与rstr
相同的值。 所以这样做应该打印你在stdout / console中发回的内容。
Console.WriteLine(rstr);
或者您可以使用StreamReader
类来包装输出流并将数据作为字符串读取。
using (var reader = new StreamReader(ctx.Response.OutputStream)
{
// Seek to origin, to read all data in the output stream,
ctx.Response.OutputStream.Seek(0, SeekOrigin.Begin);
var content = reader.ReadToEnd();
Console.WriteLine(content);
// You might not want to close the output stream in case you want to do more work with it.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.