1. Preface
This article Article Relatively short, mainly because of a piece Code . The function of this code can be called simple HTTP server or HTTP Request Interception. The function is to intercept HTTP requests and process them by yourself.
2: Code
Copy code The Code is as follows: public class httpserver: idisposable
{
Private httplistener listener;
Public void start ()
{
Listener = new httplistener ();
Listener. prefixes. Add ("http: // localhost /");
Listener. authenticationschemes = authenticationschemes. integratedwindowsauthentication | authenticationschemes. Anonymous;
Listener. Start ();
Listener. begingetcontext (getcontext, null );
}
Private void getcontext (iasyncresult AR)
{
Httplistenerrequest request;
Httplistenerresponse response;
Try
{
Httplistenercontext CTX = listener. endgetcontext (AR );
Request = CTX. request;
Response = CTX. response;
// Setup waiting for the next request
Listener. begingetcontext (getcontext, null );
}
Catch (invalidoperationexception)
{
Return;
}
Catch (httplistenerexception)
{
Return;
}
Try
{
VaR Sw = new streamwriter (response. outputstream );
Sw. Write (@ "<HTML> <body> <p> your request has been intercepted </P> </body> Sw. Flush ();
}
Finally
{
Response. outputstream. Flush ();
Response. Close ();
}
}
Public void dispose ()
{
If (listener! = NULL)
Listener. Stop ();
}
}
3: A Brief Explanation
The core of the Code is httplistener, which listens to a port. When there is a request, begingetcontext is handed over to the getcontext Method for asynchronous processing. The first internal implementation of this method is re-listening. Then perform your own processing.
What are the other functions of this code to be considered.