Write a simple web server, ASP. NET core knowledge (4), webasp.net

Source: Internet
Author: User

Write a simple web server, ASP. NET core knowledge (4), webasp.net
Preface

I tried it yesterday. Based on the research on the http protocol, we wrote a simple browser on the console. Although the browser is low, it has a better understanding of the http protocol.

After talking about the above paragraph, do you guess what I want to do? (In fact, you don't have to guess. There are all titles, and they are not blind... I just want to ridicule and tell jokes that are not nutritious. I think this is not so boring. It doesn't matter if it's not funny !)

That's right. What we want to try today is to write a web server by ourselves. The original intention is still the same as yesterday, aiming to understand something, rather than writing a lot of things.

 

First Attempt (V1.0)

1. theoretical support

In fact, I have already mentioned the theory of http in the blog post "Write a browser". I will not talk about it here.

Here we will mainly talk about Socket. This is mainly an example of how to use a Socket to create a simple code for a server program.

 

Static void Main (string [] args) {// create a new Socket. Here we use the most common TCP-based Stream Socket (Stream Socket) var socket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // bind the socket to a port socket on the host. bind (new IPEndPoint (IPAddress. any, 4530); // start the listener and set a maximum queue length socket. listen (4); // at this point, our Socket has been running, but it is just running and nothing can be done! Console. WriteLine ("Server is ready! "); Console. Read ();}

Enable debugging. To listen to a port, a prompt is displayed in windows. Just click OK.

 

From the example above, socket only listens to port 4530 and does nothing!

Like a person's ears. He will listen, but will not talk. We need an ear listening for port 4530.

However, from the perspective of communication, it is not enough for web servers to listen.

After the request comes (after listening to the request), I also need a Socket that can both listen and speak. Communicate with requests.

Why can't the socket communicate directly? No, no. He has to continue listening to new requests.

2. Talk about ideas

The main idea of this experiment is as follows.

1) Listen to port 4530

2) When the request comes, we use Socket socket = serverSocket. Accept (); To create a new socket.

3) A new socket returns a string to the requester!

Finished (read liao ).

That is to say, no matter how you request the web server of v1.0, it will return your same string! (Willful? In fact, I like it very much .)

3.Code 

Static void Main (string [] args) {// I am only responsible for listening, because when you come, I have to wait for the next one. // (It is said that the comment is written as a fairy! Can I be killed by writing like this at work? Wait until I find a job. I will try) Socket serverSocket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // bind the listening port serverSocket. bind (new IPEndPoint (IPAddress. any, 8070); // start to listen to your request serverSocket. listen (10); while (true) {Console. writeLine ("waiting for request"); // The program stays here when there is no request. // When you come, serverSocket will tell your wish to a new socket. The program continues! (Oh, literature and art) Socket socket = serverSocket. accept (); Console. writeLine ("coming request"); using (NetworkStream stream = new NetworkStream (socket) using (StreamReader reader = new StreamReader (stream) {string line; while (line = reader. readLine ())! = Null) {Console. writeLine (line); if (line. length <= 0) {break; // when a blank line is encountered, the request ends and no longer needs to be waited. // If the break is not enabled, the request is stuck in ReadLine () waiting for the browser to send subsequent data} using (NetworkStream stream = new NetworkStream (socket) using (StreamWriter writer = new StreamWriter (stream) {writer. writeLine ("HTTP/1.1 200 OK"); writer. writeLine (); writer. writeLine ("Oh, hello, hello! ") ;}Socket. Disconnect (false );}}

4. debugging

In this way, we are willful, such as qq's automatic interaction. Gao Leng always replied, "oh, hello !".

Improvement (V2.0)

1. improvement requirements

The web server of the previous version .) There is no web server at all. Chat, you can't always go on. No friends!

Therefore, the new web server improvement requirements are as follows.

1. Get the Request Path

2. The response static page can be returned Based on the file corresponding to the Request Path!

Why is there a proper family of children.

Let's not talk much about it. Just start typing code!

2. Implementation

Static void Main (string [] args) {Socket serverSocket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); serverSocket. bind (new IPEndPoint (IPAddress. any, 8080); serverSocket. listen (10); while (true) {Console. writeLine ("waiting for request"); Socket socket = serverSocket. accept (); Console. writeLine ("coming request"); string firstLine; using (NetworkStream stream = new NetworkStream (socket) using (StreamReader reader = new StreamReader (stream) {// This is an extra sentence in Version 1.0. // Think about the http Request Message format. The first line contains a file path! FirstLine = reader. ReadLine (); string line; while (line = reader. ReadLine ())! = Null) {Console. writeLine (line); if (line. length <= 0) {break; // when a blank line is encountered, the request ends and no longer needs to be waited. // If the break is not enabled, the request is stuck in ReadLine () waiting for the browser to send subsequent data }}// obtain the request path string [] strs = firstLine. split (''); // The url gets a string like index.html. String url = strs [1]; Console. writeLine ("url =" + url); using (NetworkStream stream = new NetworkStream (socket) using (StreamWriter writer = new StreamWriter (stream )) {// Why do we need to specify an absolute path? What does [physical path] on a normal web Server mean. It should be understood. String filePath = @ "C: \ Users \ WinterT \ Desktop \ message box, JBar" + url; Console. writeLine ("filePath =" + filePath); if (File. exists (filePath) {writer. writeLine ("HTTP/1.1 200 OK"); writer. writeLine (); string html = File. readAllText (filePath); Console. writeLine (html); writer. write (html);} else {writer. writeLine ("HTTP/1.1 404 not found"); writer. writeLine (); writer. write ("404, not found") ;}} socket. disconnect (false );}}

3. debugging

The request is an existing html page on my computer. It is displayed successfully!

 

Closing comments

 

(It means I am very happy)

In fact, this experiment still concluded that the http protocol is request/response. The text is passed!

There are still many improvements to this software. But this is not the point. The key point is to understand something. web server is just a form, not a purpose!

 

PS:I just found out. I want to add it now.

I don't know if you noticed this.

On my web server, each time I input a request from a browser url, two requests are displayed on the server's console.

So what is the extra request? Let's take a closer look!

Yes, that's right. The browser is requesting the website icon!

That is to say, if we want to create a website icon, place it directly in the root directory of the website.

The favicon. ico file is ready !!

 

 

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.