Этот проект может помочь вам создать веб-сервер с нуля: MiniHttpd: an HTTP web server library используя чистый TCP/IP
Но вместо того, чтобы иметь дело с большим количеством ненужных деталей таких как разбор заголовков, сжатие, аутентификация, ssl и т. д. Я бы использовал встроенный класс HttpListener.
Вот упрощенная (но работает) многопоточный WebServer
void CreateWebServer()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://*:8080/");
listener.Start();
new Thread(
() =>
{
while (true)
{
HttpListenerContext ctx = listener.GetContext();
ThreadPool.QueueUserWorkItem((_) => ProcessRequest(ctx));
}
}
).Start();
}
void ProcessRequest(HttpListenerContext ctx)
{
string responseText = "Hello";
byte[] buf = Encoding.UTF8.GetBytes(responseText);
Console.WriteLine(ctx.Request.Url);
ctx.Response.ContentEncoding = Encoding.UTF8;
ctx.Response.ContentType = "text/html";
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
ctx.Response.Close();
}
EDIT
Я изменил серверу немного, чтобы сделать его провести RESTful WebService (MyService
). Он возвращает результат как Json. Вы можете назвать это http://localhost:8080/?method=Calc&i=5&j=4
(я просто пропустил множество проверок ошибок)
public class MyService
{
public Result Calc(int i, int j)
{
return new Result() { Addition = i + j, Multiplication = i * j };
}
}
public class Result
{
public int Addition { set; get; }
public int Multiplication { set; get; }
}
void CreateWebServer()
{
MyService service = new MyService();
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://*:8080/");
listener.Start();
new Thread(
() =>
{
while (true)
{
HttpListenerContext ctx = listener.GetContext();
ThreadPool.QueueUserWorkItem((_) => ProcessRequest(ctx,service));
}
}
).Start();
}
void ProcessRequest(HttpListenerContext ctx,MyService service)
{
try
{
string responseText = Execute(ctx, service);
byte[] buf = Encoding.UTF8.GetBytes(responseText);
ctx.Response.ContentEncoding = Encoding.UTF8;
ctx.Response.ContentType = "application/json";
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch
{
ctx.Response.StatusCode = (int) HttpStatusCode.NotFound;
}
ctx.Response.Close();
}
string Execute(HttpListenerContext ctx, MyService service)
{
System.Collections.Specialized.NameValueCollection nv = HttpUtility.ParseQueryString(ctx.Request.Url.Query);
MethodInfo mi = service.GetType().GetMethod(nv["method"]);
object[] parameters = mi.GetParameters()
.Select(pi => Convert.ChangeType(nv[pi.Name], pi.ParameterType))
.ToArray();
return JsonConvert.SerializeObject(mi.Invoke(service, parameters));
}
Уверен, что это возможно. Однако «хочу ли я снова реализовать HTTP снова?» это еще один вопрос. – Jon
Этот проект использует TcpListener для обслуживания HTTP-запросов: http://www.codeproject.com/Articles/1505/Create-your-own-Web-Server-using-C –
Нет, это не так. Если вы обрабатываете HTTP-запросы, у вас есть веб-сервер. Вы спрашиваете: «Как я могу создать свой собственный веб-сервер». – svick