基于C#实现一个最简单的HTTP服务器实例

2019-12-26 11:28:29刘景俊

    public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) {
        Console.WriteLine("POST request: {0}", p.http_url);
        string data = inputData.ReadToEnd();
 
        p.outputStream.WriteLine("<html><body><h1>test server</h1>");
        p.outputStream.WriteLine("<a href=/test>return</a><p>");
        p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);
    }
}

 

当开始处理一个简单的请求时,我们就需要单独启动一个线程来监听一个端口,比如8080端口:

复制代码 HttpServer httpServer = new MyHttpServer(8080);
Thread thread = new Thread(new ThreadStart(httpServer.listen));
thread.Start();

 

如果你编译运行这个项目,你会在浏览器http://www.easck.com/>         while (is_active) {                
            TcpClient s = listener.AcceptTcpClient();
            HttpProcessor processor = new HttpProcessor(s, this);
            Thread thread = new Thread(new ThreadStart(processor.process));
            thread.Start();
            Thread.Sleep(1);
        }
    }
 
    public abstract void handleGETRequest(HttpProcessor p);
    public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
}

 

这样,一个新的tcp连接就在自己的线程中被HttpProcessor处理了,HttpProcessor的工作就是正确解析HTTP头,并且控制正确实现的抽象方法。下面我们来看看HTTP头的处理过程,HTTP请求的第一行代码如下:

 

复制代码 GET /myurl HTTP/1.0

 

在设置完process()的输入和输出后,HttpProcessor就会调用parseRequest()方法。