// Based on Request, Headers, and Content, retrieve a response. private void RetrieveResponse(HTTPRequest request, HTTPHeader header, StreamReader stream, out HTTPResponse response) { // We're going to retrieve the rest of the request. string content = string.Empty; // While there's still data. while (stream.Peek() != -1) { // Retrieve it. content += stream.Read(); } // Process our response. response = HTTPResponse.Process(request, header, content); }
private void Work() { // bool closed = false; // Retrieve the client's ip address. IPAddress ip = ((IPEndPoint)this.tcp.Client.RemoteEndPoint).Address; // Get the stream. StreamReader stream = new StreamReader(this.tcp.GetStream()); // Our HTTP data. HTTPRequest request = null; HTTPHeader header = null; HTTPResponse response = null; // Loop while the connection is still open. while (closed == false) { // Check if there's new data on our network stream. if (stream.Peek() != -1) { // Handle the request. RetrieveRequest(stream, out request); if (request != null) { RetrieveHeaders(stream, out header); RetrieveResponse(request, header, stream, out response); Send(response); request = null; header = null; response = null; } this.tcp.Close(); closed = true; } } }
// Try to get the headers from the network stream. private void RetrieveHeaders(StreamReader stream, out HTTPHeader header) { // Start with an empty string. string process = string.Empty; // While there's still data. while (stream.Peek() != -1) { // Read the next line. process += stream.ReadLine() + '\n'; // If line is empty, break out of our loop. if (string.IsNullOrWhiteSpace(process) == true) { break; } } // Process the headers. header = HTTPHeader.Process(process); }
public HTTPResponse(HTTPRequest request, HTTPHeader header, string content) { string html = string.Empty; // HTML html += "<h2>Request</h2><p>"; html += "Method: " + request.method + "<br />"; html += "URL: " + request.url_string + "<br />"; html += "HTTP Version: " + request.version + "<br />"; html += "</p>"; html += "<h2>Headers</h2><p>"; foreach (KeyValuePair <string, string> item in header.headers) { html += item.Key + ": " + item.Value + "<br />"; } html += "</p>"; if (string.IsNullOrWhiteSpace(content) == false) { html += "<h2>Content</h2><p>"; html += content + "<br />"; html += "</p>"; } // Response message += "HTTP/1.1" + " " + "404" + " " + "Not Found" + '\n'; html += "<h2>Response</h2><p>"; html += message; html += "</p>"; message += "Server" + ": " + "C# Website Server (x64)" + '\n'; message += "Content-Length" + ": " + html.Length.ToString() + '\n'; message += "Content-Type" + ": " + "text/html" + '\n'; message += "Connection" + ": " + "closed" + '\n'; message += '\n'; message += html; }
public static HTTPResponse Process(HTTPRequest request, HTTPHeader header, string content) { return(new HTTPResponse(request, header, content)); }