today I found the following code: World’s smallest web server
World’s smallest web server
It’s always fun to play with .Net, the HTTP Listener class in .Net 2.0 makes it really easy. With this little block of code you can setup a very simple (multithreaded) web server…
public class Server
{
private static System.Threading.AutoResetEvent listenForNextRequest = new System.Threading.AutoResetEvent(false);
protected Server()
{
_httpListener = new HttpListener();
}
private HttpListener _httpListener;
public string Prefix { get; set; }
public void Start()
{
if (String.IsNullOrEmpty(Prefix))
throw new InvalidOperationException("No prefix has been specified");
_httpListener.Prefixes.Clear();
_httpListener.Prefixes.Add(Prefix);
_httpListener.Start();
System.Threading.ThreadPool.QueueUserWorkItem(Listen);
}
internal void Stop()
{
_httpListener.Stop();
IsRunning = false;
}
public bool IsRunning { get; private set; }
private void ListenerCallback(IAsyncResult result)
{
HttpListener listener = result.AsyncState as HttpListener;
HttpListenerContext context = null;
if (listener == null)
// Nevermind
return;
try
{
context = listener.EndGetContext(result);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
return;
}
finally
{
listenForNextRequest.Set();
}
if (context == null)
return;
ProcessRequest(context);
}
// Loop here to begin processing of new requests.
private void Listen(object state)
{
while (_httpListener.IsListening)
{
_httpListener.BeginGetContext(new AsyncCallback(ListenerCallback), _httpListener);
listenForNextRequest.WaitOne();
}
}
}
No comments:
Post a Comment