Hi everyone!
For a 'learning' experience, I'm looking to write my own webserver in C#. I know most people would just write me down and say "Why are you wasting your time, just use a premade webserver!". But that's not the point - the point is to learn. I want to know how the world of HTTP works.
So far, this is my code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Reflection;
using System.IO;
namespace CoolioServerWeb
{
class Program
{
public static HttpListener listener = new HttpListener();
public static string startUpPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
public static void Main(string[] args)
{
listener.Start();
listener.Prefixes.Add("http://192.168.2.4/");
Thread t = new Thread(new ThreadStart(clientListener));
t.Start();
Console.Write(">");
while (true)
{
string s = Console.ReadLine();
Console.Write(">");
}
}
public static void clientListener()
{
while (true)
{
try
{
HttpListenerContext request = listener.GetContext();
ThreadPool.QueueUserWorkItem(processRequest, request);
}
catch (Exception e) { Console.WriteLine(e.Message); Console.Write(">"); }
}
}
public static void processRequest(object listenerContext)
{
try
{
var context = (HttpListenerContext)listenerContext;
string filename = Path.GetFileName(context.Request.RawUrl);
string path = Path.Combine(startUpPath, filename);
byte[] msg;
if (!File.Exists(path))
{
Console.WriteLine("Client requested nonexistent file, sending error...");
Console.Write(">");
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
msg = File.ReadAllBytes(startUpPath + "\\webroot\\error.html");
}
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);
}
catch
{
}
}
}
}
But the problem is that when I go type in http://192.168.2.4 (my internal IP) all I get is plain text - for some reason, images don't show up. Is it because I have to link the images as well or something?
My guess is that all I'm doing is sending the text, but not any of its dependencies (the images and CSS). How can I resolve this? Thanks in advance!