I remember trying to create my own Apache, PHP, MySQL Server with C# a couple years ago, however I never kept on the project for long. I don't remember where this code comes from but I had saved it just in case. Its a basic HTTP Server in C#. Works kinda like wamp or xampp minus the apache, mysql, and php aspects. Maybe you could find a way to add those in? This project could have a lot of potential. I'll definitely have to look into it more when I have time.
I don't take credit for this code.
PHP Code:
using System.Net;
using System.Net.Sockets;
using System.IO;
using System;
using System.Threading;
using System.Text;
class WebServer
{
HttpListener _listener;
string _baseFolder;
private System.Threading.AutoResetEvent resetEvent = new System.Threading.AutoResetEvent(false);
private bool running = true;
public WebServer(string uriPrefix, string baseFolder)
{
System.Threading.ThreadPool.SetMaxThreads(50, 1000);
System.Threading.ThreadPool.SetMinThreads(50, 50);
_listener = new HttpListener();
_listener.Prefixes.Add(uriPrefix);
_baseFolder = baseFolder;
}
public void Start()
{
new System.Threading.Thread(() =>
{
_listener.Start();
while (running)
{
_listener.BeginGetContext(asyncResult =>
{
resetEvent.Set();
try
{
System.Net.HttpListenerContext context = _listener.EndGetContext(asyncResult);
context.Response.Headers[System.Net.HttpResponseHeader.CacheControl] = "no-cache, no-store";
context.Response.Headers[System.Net.HttpResponseHeader.Expires] = "-1";
context.Response.Headers[System.Net.HttpResponseHeader.LastModified] = System.DateTime.MinValue.ToString();
context.Response.Headers[System.Net.HttpResponseHeader.Pragma] = "no-cache";
context.Response.SendChunked = false;
try
{
string filename = Path.GetFileName(context.Request.RawUrl);
string path = Path.Combine(_baseFolder, filename);
byte[] msg;
if (!File.Exists(path))
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
msg = Encoding.UTF8.GetBytes("Sorry, that page does not exist");
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
msg = File.ReadAllBytes(path);
}
context.Response.ContentLength64 = msg.Length;
using (Stream s = context.Response.OutputStream)
s.Write(msg, 0, msg.Length);
}
finally
{
}
}
catch (System.Exception ex)
{
}
},
null);
resetEvent.WaitOne();
}
}) { IsBackground = true }.Start();
}
public void Stop()
{
running = false;
_listener.Stop();
resetEvent.Set();
}
}
Results 1 to 1 of 1
Thread: [C#] Basic HTTP Web Server
- 15 Aug. 2014 10:46pm #1
[C#] Basic HTTP Web Server