public static bool Start(int port, string responseTemplate) { Message message = new Message(); bool success = true; //make a 1mb buffer byte[] buffer = new byte[1024]; //translated to string form from data recieved from client socket. StringBuilder sb = new StringBuilder(); //the HOST field in the Request line of the HTTP request string requestedURL; try { //listens for connection on specified port parameter on all //network interfaces. I.e wired and wireless assigned IP addresses TcpListener tcpListener = new TcpListener(IPAddress.Any, port); //start listening tcpListener.Start(); /********NOTE: These using statements call Dispose() at the end of the block implicitly ******/ using (TcpClient tcpClient = tcpListener.AcceptTcpClient()) using (NetworkStream stream = tcpClient.GetStream()) { //read the networkstream's data into buffer //loop to recieve all data sent by the client. int bytesRead = 0; string dataRead = ""; string content = ""; do { bytesRead = stream.Read(buffer, 0, buffer.Length); dataRead = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); content = message.CheckValidity(dataRead); while (content != "") { content = message.CheckValidity(content); if (message.State is ErrorState) { return(false); } } sb.Append(dataRead); } while(stream.DataAvailable); //check if we reached finalstate, if no return false. if (!(message.State is FinalState)) { return(false); } //at this point we will have the full data. requestedURL = WebServer.ParseHttpRequest(sb.ToString()); //NOTE: We are safe to do this parse and check because we've reach an accepting state. if (requestedURL == "") { //No Host: was specified. success = false; } else { string formattedResponse = string.Format(responseTemplate, "11346814", DateTime.Now, requestedURL); byte[] msg = System.Text.Encoding.ASCII.GetBytes(formattedResponse); stream.Write(msg, 0, msg.Length); } //close the tcp connection with the client since we are done. tcpClient.Close(); } } catch (SocketException) { success = false; } return(success); }