听取浏览器的请求

使用以下代码:

HttpListener listener = new HttpListener(); //listener.Prefixes.Add("http://*:80/"); listener.Prefixes.Add("http://*:8080/"); listener.Prefixes.Add("http://*:8081/"); listener.Prefixes.Add("http://*:8082/"); listener.Start(); HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; 

该程序挂起在GetContext(); 尽管在IE和Firefox中加载了http(而不是https)页面。

当我取消注释第一行时,我收到错误:

无法侦听前缀’http:// *:80 /’,因为它与计算机上的现有注册冲突。

那么我该如何收听浏览器的请求呢?

@LB我想写一个“代理”

不要重新发明轮子,只需使用FiddlerCore

 public class HttpProxy : IDisposable { public HttpProxy() { Fiddler.FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest; Fiddler.FiddlerApplication.Startup(8764, true, true); } void FiddlerApplication_BeforeRequest(Fiddler.Session oSession) { Console.WriteLine(String.Format("REQ: {0}", oSession.url)); } public void Dispose() { Fiddler.FiddlerApplication.Shutdown(); } } 

编辑

你可以从这个矩形轮开始:)

 void SniffPort80() { byte[] input = new byte[] { 1 }; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); socket.Bind(new IPEndPoint(IPAddress.Broadcast, 80)); socket.IOControl(IOControlCode.ReceiveAll, input, null); byte[] buffer = new byte[0x10000]; Task.Factory.StartNew(() => { while (true) { int len = socket.Receive(buffer); if (len <= 40) continue; //Poor man's check for TCP payload string bin = Encoding.UTF8.GetString(buffer, 0, len); //Don't trust to this line. Encoding may be different :) even it can contain binary data like images, videos etc. Console.WriteLine(bin); } }); } 

可能正在使用此端口…在命令行上运行netstat -ano,您将看到正在使用的端口列表及其进程ID。

我不知道,为什么GetContext(); 挂起,因为有关listerner变量发生的事情的信息太少,但端口80的问题通常是由Skype引起的,因为它默认使用端口80。 要解决此问题,请打开Skype的首选项,转到高级 – >连接并取消选中“使用端口80和443作为传入连接的替代方法”。

我会考虑查看这个包http://www.nuget.org/packages/Microsoft.AspNet.WebApi.OwinSelfHost/它使用了HttpListener,并使用WebApi HttpMessageHandler创建代理非常容易。

它挂起,因为GetContext()正在等待接收请求,如其文档中所述:

此方法在等待传入请求时阻塞。 如果希望异步处理传入请求(在不同的线程上)以便应用程序不会阻塞,请使用BeginGetContext方法。

有关详细信息,请参阅: https : //msdn.microsoft.com/en-us/library/system.net.httplistener.getcontext(v=vs.110).aspx

使用异步模型往往很复杂,另一种选择是在不同的线程中运行所有代码,但这取决于您的目标。

+替换前缀中的*

 listener.Prefixes.Add("http://+:8080/");