Access Home page for developing the HTTP server family using C #

Source: Internet
Author: User
Tags browser cache

?? Hello friends Everyone, I am Qin Yuanpei, welcome to pay attention to my blog, my blog address is http://qinyuanpei.com. In the first installment of this series, we focused on understanding and understanding the HTTP protocol, and implemented an interactive Web server that allows the server to return and output a simple "Hello world" when the client accesses the server. Now that this server looks very rudimentary, we need to continue to work on this basis. Today we want to add page support to this server, that is, when we visit this server, it can show us a customized server home page. Typically, the home page of a website is defined as index.html, and in dynamic website technology it can be defined as index.php. Understanding these will help us understand the nature of web technologies, and for the sake of our research here, let's take the simplest static pages for example.

Mistake

?? The first thing we can realize is that the homepage of a website is a page which is displayed by default to the visitor, so for the server, it needs to know two things, the first client is currently requesting this page is not the homepage, the second service side should return what content to the client. For both of these issues, we can find the answer in the Web server we are designing today. Because the default request method in the HTTP protocol is get, we can easily know, based on the instance of HttpRequest, the method type of the current request and the requested address. Let's look at a simple client request message:

get / http/1.1  accept : text/html, application/ Xhtml+xml, IMAGE/JXR, */*  accept-language :  zh-hans-cn,zh-hans;q=0.5  user-agent :  mozilla/5.0 (Windows NT 10.0) applewebkit/537.36 (khtml, like Gecko) chrome/46.0.2486.0 safari/537.36 edge/13.10586
     accept-encoding : gzip, deflate  host : localhost:4040  connection : keep-alive   

Here we can see very clearly that the client's current request is a get type, and its requested address is "/", which means that the request page is the home page, and actually we combine the host field with this address to get a full address, This is why we use relative addresses when we write hyperlinks in the HTML structure. Well, after we understand the specific workings of these two things, let's continue to write logic to show how a site's home page is presented to visitors.

 Public Override void Onget(HttpRequest request) {//Determine Request type and request page    if(Request. Method = ="GET"&& request. URL = ="/")    {//Structure Response messageHttpResponse response;//Determine if the home file exists, read the home file if it exists otherwise return 404        if(! File.exists (ServerRoot +"Index.html") {response =NewHttpResponse (", Encoding.UTF8); Response. StatusCode ="404"; Response. Content_Type ="Text/html"; Response. Server ="Exampleserver"; }Else{response =NewHttpResponse (file.readallbytes (ServerRoot +"Index.html"), Encoding.UTF8); Response. StatusCode =" the"; Response. Content_Type ="Text/html"; Response. Server ="Exampleserver"; }//Send responseProcessResponse (Request.    Handler, response); }}

Notice here that we first determine whether the current client is requesting the home page based on the request method and the request address. Then we determine whether there is a index.html file in the server directory, if the file exists to read the file and return to the client, otherwise we will return to the client a state of 404, familiar with the web development of the friend should know that the status code indicates that the request resource could not be found, similarly we can think of the status code has 200 , 501, and so on, usually the definition of these status codes is this:
* 1XX: Indicates information-Indicates that the request has been received and continues processing.
* 2XX: Success-Indicates that the request has been successfully accepted, understood, and processed.
* 3XX: Redirect-Indicates that a further action is required to complete the request.
* 4XX: Client Error-Indicates a request error or cannot be implemented.
* 5XX: Service-side error-Indicates that the server did not provide the correct response.

In particular, the common status codes are described as follows:

Status code status description
OK client request succeeded
Bad Request client request error and cannot be serviced
401 Unauthorized request unauthorized use of the Www-authenticate header field
403 Forbidden server received a request but refused to provide service
404 Not Found request resource does not exist
Internal Server error server has unexpected errors
503 Server unavailable server is currently unable to process client requests

In order to simplify the requirements, we assume that there is only one home page file index.html in the server directory, in fact, such as IIS, Apache and other large server software are supporting multiple home page files, but also support static pages and dynamic pages, so here involves a priority problem, Whether in Apache or IIS, we can find the option to set the page priority. The so-called priority, in fact, is a sort of the importance of these home page files, in the actual design process, will first read the higher priority of the home page file, if the file does not exist and then back to the second, and so on. When reading the home page file, we need to be aware of the encoding type, because both the client and the server in their own header information in the declaration of its acceptable encoding type, so in response to the request should be aware of the client and clients should be consistent, so as to avoid the "'re same page" problem occurs, Thus improving communication efficiency. We are talking about technology here, but people are not so ah, I feel that we live and work 90% of the time are used to communicate, but this precisely illustrates the importance of communication ah. OK, let's test the page we wrote below:

Dragon Latent Deep-abyss

?? Hey? This page shows how the results are not the same as what we expected ah, it seems that this is a result of the loss of the style of the error Ah, not only that we found that the picture on the page is also missing. First we check the static page is not a problem, how is this possible? Since this is a static page generated by the blogger using Hexo, we have to start rethinking our design after the problem of excluding the page itself. Let's think about the question: Is there only static pages interacting with the server while the browser is loading a page? It's obviously not, because fools know that a Web page has at least three parts of HTML, CSS, and JavaScript, so we decided to take a closer look at chrome to see what happens to the browser as it loads the page. Press "F12" to open the developer tool to listen to the Web page:

?? wtf! It feels like it's a crazy place, isn't it? You didn't think the server would respond to so many requests here? So we are smart to think that as long as the response to the static page request is good, this is completely dead! My understanding here is that the server reads it back to the client after reading it, so this part of the response is completely visible to the client, and the associated CSS style and JavaScript script in the page may be downloaded locally through the browser cache. Then we refer to the relative path and apply it to the whole page, and in order to distinguish these different types of resources, we need to indicate the type of the content in the Content-type field in the response message, so now we know that there are a lot of associated resources in the first page of the request. These resources must be fed back to the client via response messages, followed by different types that are specifically reflected in the Content-type field of the response message. Therefore, we modify and refine the code based on the first paragraph, and finally write the following code:

 Public Override void Onget(HttpRequest request) {if(Request. Method = ="GET")    {///   get client request address          ///Link Form 1: "Http://localhost:4050/assets/styles/style.css" means access to the specified file resource,        ///   Read the/assets/styles/style.css file under the server directory at this time.           ///Link Form 2: "http://localhost:4050/assets/styles/" means access to the specified page resource,        ///   Read the/assets/styles/style.index file under the server directory at this time.         404 Status Code should be returned when the file does not exist        stringRequesturl = Request.        URL; Requesturl = Requesturl.replace ("/",@"\"). Replace ("\\..","");//Determine if an extension exists in the address        stringExtension = Path.getextension (Requesturl);//Based on two different links according to the extension        stringRequestFile =string. Empty;if(Extension! ="") {RequestFile = ServerRoot + Requesturl; }Else{requestfile = ServerRoot + Requesturl +"Index.html"; }//Construct HTTP responseHttpResponse response = Responsewithfile (RequestFile);//Send responseProcessResponse (Request.    Handler, response); }}

Notice that I wrote two different forms of link analysis in the code:

    • Link Form 1: "Http://localhost:4050/assets/styles/style.css" means access to the specified file resource, at which point the/assets/styles/style.css file under the server directory is read.

    • Link Form 2: "http://localhost:4050/assets/styles/" means access to the specified page resource, at which point the/assets/styles/style.index file under the server directory is read.

?? First we judge that these two forms are based on the extension, so that we can get a pointer to the destination file address RequestFile. Here is an auxiliary method Responsewithfile, which is a method of constructing a response message from a file, whose return type is a httpresponse, which will be returned to the client 404 error code when the file does not exist, and we'll look at how it's implemented in detail:

//   <summary> ///   Use file to provide HTTP response//   </summary> //   <param name= "filename" > filename </param> PrivateHttpResponseResponsewithfile(stringFileName) {//Prepare HTTP response MessagesHttpResponse response;//Get the file name extension to determine the content type    stringExtension = Path.getextension (fileName);//Get current content type    stringContentType = getcontenttype (extension);returns 404 If the file does not exist otherwise reads the contents of the file    if(! File.exists (FileName)) {response =NewHttpResponse (", Encoding.UTF8); Response. StatusCode ="404"; Response. Content_Type ="Text/html"; Response. Server ="Exampleserver"; }Else{response =NewHttpResponse (File.readallbytes (fileName), Encoding.UTF8); Response. StatusCode =" the"; Response.         Content_Type = ContentType; Response. Server ="Exampleserver"; }/Return DatareturnResponse;}

Similarly, because we need to indicate the type of resource in the response message, we use an auxiliary method called getContentType, which is defined as follows, which is only a common type of content-type to implement, Interested friends can learn more about their own content and expand on this basis:

//   <summary> ///   get content type by file extension//   </summary> //   <param name= "extension" > file extension </param> ///   <returns></returns> protected string getContentType(stringextension) {stringReval =string. Empty;if(string. IsNullOrEmpty (extension))return NULL;Switch(extension) { Case ". htm": Reval ="Text/html"; Break; Case ". html": Reval ="Text/html"; Break; Case ". txt": Reval ="Text/plain"; Break; Case ". css": Reval ="Text/css"; Break; Case ". png": Reval ="Image/png"; Break; Case ". gif": Reval ="Image/gif"; Break; Case ". jpg": Reval ="Image/jpg"; Break; Case ". jpeg": Reval ="Image/jgeg"; Break; Case ". zip": Reval ="Application/zip"; Break; }returnReval;}
See the Rainbow after the rain

?? Okay, so far, we've basically come to the end of writing about static Web servers! In fact, this article is not particularly well written, because I almost constantly deny the self-situation, while debugging while writing this article. The whole article summarized down actually two points, first, the Web server when loading a page will be launched countless request messages, in addition to the page related to the request message is mostly related to resource requests, so the HTML page optimization is actually from the resource load this place to start. Second, different resources have different types, specifically in response to the Content-type field of the message, the construction of the correct content-type can let the client understand what this is a resource. Okay, now we can be calm and free to verify our labor results, here I use my local Hexo generated static blog as an example to demonstrate my web server, assuming my blog is stored in the "D:\Hexo\public" path, So I can set up my server directory directly in the Web server:

servernew ExampleServer("127.0.0.1",4050);server.SetServerRoot("D:\\Hexo\\public");server.Start();

Now open the browser to see:

So exciting time, let us tage long line, the dream of sustainable, next time see!

Access Home page for developing the HTTP server family using C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.