[C # network programming series] Topic 3: custom web servers

Source: Internet
Author: User

Preface:

After a brief introduction to the network layer protocol and HTTP protocol in the previous topic, I believe that you have a general understanding of the protocols in the network. This topic will define a Web server for the HTTP protocol, you can view the desired webpage by entering a URL in the browser. In this process, the browser is only a client.Program) Send user requests to the server through the HTTP protocol. The server receives the sent HTTP requests and then processes and responds to the requests, finally, the response content is sent to the client (the browser acts as the user agent client), and the browser then interprets and displays the response content (generally an HTML file. This is a complete user request/response model. This topic describes a simple Web server, and some other large Web servers (IIS and Apache) work like this, this topic is just a brief introduction to the implementation principles of web servers.

 

I. socket programming to implement a simple Web Server

The concept of socket is proposed in UNIX systems. In the Unix era, to solve the Programming Problem of the transport layer, Unix provides a network operation method similar to file operations-socket. Through socket, we can operate likeCompositionNetwork Programming is completed by opening, writing, reading, closing, and other operations, so that network programming can be integrated into file operations, which makes it easier for us to write network applications. It should be noted that the Protocol at the application layer must be specially processed by network programs. The socket is not responsible for the protocol at the application layer, but only for the protocol at the transmission layer.

Now we will introduce the concept of port. In the same network address, to distinguish different applications using the same protocol, assign a number to different applications, we will change this number to the network port number (that is, to distinguish different processes in the same network address ). The port number is a two-byte integer, so the value range is 0 ~ 65535, these port numbers are divided into three types:

    1. The first category ranges from 0 ~ 1023, known as a well-known port number, is used by a specific network program. For example, TCP uses port 80 to complete HTTP transmission.
    2. The range of the second category is 1024 ~ 49151 is called the registration port, which is generally not used in the program.
    3. The third category is 49152 ~ 65535 is called a private port. These ports can be used by common user programs.

In the development of network applications using sockets, there is also the concept of endpoints. in the network, an application on the network can be uniquely identified through IP addresses, protocols, and port numbers, the combination of IP addresses and ports is called an endpoint ). Each socket needs to be bound to one endpoint to communicate with other endpoints.

After introducing some basic concepts, the following describes how to use socket programming to implement a simple Web server. In this example, a fixed static page is returned to the browser to implementCodeAs follows:

 Using  System;  Using  System. net;  Using  System. net. Sockets;  Using  System. text;  Namespace  Webserver {  ///   <Summary>     ///  Implement a simple Web Server  ///  The server returns a static html page to the requested browser.  ///   </Summary>      Class  Program {  Static   Void Main ( String  [] ARGs ){  //  Obtain the IP address of the local machine, that is, 127.0.0.1. IPaddress localaddress = IPaddress. loopback;  //  Create a breakpoint that can be accessed. "49155" indicates the port number. If this parameter is set to 0, it indicates using an idle port number allocated by the system. Ipendpoint endpoint = New Ipendpoint (localaddress, 49155  ); //  Create a socket object and use an IPv4 address. The data communication type is data stream and the transmission control protocol is TCP. Socket socket = New  Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );  //  Bind the socket to the breakpoint  Socket. BIND (endpoint );  //  Set the length of the connection queue Socket. Listen ( 10  );  While ( True  ) {Console. writeline (  "  Wait an CONNECT request...  "  );  // Start listening. This method will block thread execution until it receives a connection request from a client. Socket clientsocket = Socket. Accept ();  //  Output client address Console. writeline ( "  Client address is: {0}  "  , Clientsocket. remoteendpoint );  //  Read the client request data and save it to an array.                  Byte [] Buffer = New   Byte [ 2048  ];  Int Incluelength = clientsocket. Receive (buffer, 2048  , Socketflags. None );  String Requeststring = encoding. utf8.getstring (buffer, 0  , Cancelength );  //  Output request message on the server side  Console. writeline (requeststring );  //  Make corresponding content on the server side  //  Response status line                  String Statusline = "  HTTP/1.1 200 OK \ r \ n  "  ;  Byte [] Responsestatuslinebytes = Encoding. utf8.getbytes (statusline );  String Responsebody = " <HTML>   "  ;  String Responseheader = String  . Format (  "  Content-Type: text/html; charset = UTf-8 \ r \ ncontent-length: {0} \ r \ n  "  , Responsebody. Length );  Byte [] Responseheaderbytes = Encoding. utf8.getbytes (responseheader );  Byte [] Responsebodybytes = Encoding. utf8.getbytes (responsebody );  // Send status lines to the client  Clientsocket. Send (responsestatuslinebytes );  //  Send Response Header information to the client  Clientsocket. Send (responseheaderbytes );  //  Empty lines of the sending header and content Clientsocket. Send ( New   Byte [] { 13 , 10  });  //  Want the client to send the subject  Clientsocket. Send (responsebodybytes );  //  Disconnect  Clientsocket. Close (); console. readkey ();  Break ;}  //  Disable the server  Socket. Close ();}}} 

Running result:

First run the interface after the server:

Enter http: // localhost: 49155/in the browser and you will see the following results:

The output displayed on the server side is:

Here is just a simple implementation of a web server function. Of course, the actual Web Server obtains the request file type, request file name, and request directory information through the HTTP request sent by the user, the Web server then searches for the requested file from the physical directory of the server based on the request information. If the requested file is found in the server, the server then sends the response content to the client. Here, we only use this simple web server to let everyone understand the request/Response Model and the working principle of the Web server. Some complex web servers are also used to expand some other functions on this basis.

Ii. tcplistener-based Web Server

On the. NET platform, to simplify network programming,. Net further encapsulates sockets. The encapsulated classes are stored in the system. net. Sockets namespace.TcplistenerClass andTcpclientClass, useTcplistenerClass is used to listen to and receive incoming connection requests. In the constructor of this class, you only need to pass a set of network endpoint information to prepare the listening parameters, you do not need to set the network protocol and other details. After the start method is called, The Listener starts to work (the socket is indirectly called. the accepttcpclient method will block the process until a client sends a connection request. This method returns

Encapsulated socketTcpclientObject, and delete the Client Connection Request from the incoming connection queue. In this case, the tcpclient object is used to communicate with the client.

The following is a simple web server code based on tcplistener and tcpclient:

 Using  System;  Using  System. net;  Using  System. net. Sockets;  Using  System. text;  Namespace  Tcpwebserver {  Class Program {  Static   Void Main ( String  [] ARGs ){  //  Obtain the IP address of the local machine, that is, 127.0.0.1. IPaddress localaddress = IPaddress. loopback;  //  Create a breakpoint that can be accessed. "49155" indicates the port number. If this parameter is set to 0, it indicates using an idle port number allocated by the system. Ipendpoint endpoint = New Ipendpoint (localaddress, 49155  );  //  Create a TCP listener Tcplistener = New  Tcplistener (endpoint );  // Start listening  Tcplistener. Start (); console. writeline (  "  Wait an CONNECT request...  "  );  While ( True  ){  //  Waiting for customer connection Tcpclient client = Tcplistener. accepttcpclient ();  If (Client. Connected = True  ){  //  The output has established a connection. Console. writeline ( "  Created connection  " );}  //  Obtain a network stream object  //  This network stream object encapsulates socket input and output operations  //  At this time, the system returns the Response Message by writing the network stream object.  //  Obtain the request message by reading the network stream object Networkstream netstream = Client. getstream ();  //  Read the client request data and save it to an array.                  Byte [] Buffer = New   Byte [ 2048  ];  Int Required elength = netstream. Read (buffer, 0 , 2048 );  String Requeststring = encoding. utf8.getstring (buffer, 0  , Cancelength );  //  Output request message on the server side  Console. writeline (requeststring );  //  Make corresponding content on the server side  //  Response status line                  String Statusline = "  HTTP/1.1 200 OK \ r \ n  "  ;  Byte [] Responsestatuslinebytes = Encoding. utf8.getbytes (statusline );  String Responsebody = " <HTML>   "  ;  String Responseheader = String  . Format (  "  Content-Type: text/html; charset = UTf-8 \ r \ ncontent-length: {0} \ r \ n  "  , Responsebody. Length );  Byte [] Responseheaderbytes = Encoding. utf8.getbytes (responseheader );  Byte [] Responsebodybytes = Encoding. utf8.getbytes (responsebody ); //  Write status row Information Netstream. Write (responsestatuslinebytes, 0  , Responsestatuslinebytes. Length );  //  Write Response Header Netstream. Write (responseheaderbytes, 0  , Responseheaderbytes. Length );  //  Empty lines between the response header and content are written. Netstream. Write ( New   Byte [] { 13 , 10 }, 0 , 2  );  //  Write the response content Netstream. Write (responsebodybytes, 0  , Responsebodybytes. Length );  //  Close the connection to the client  Client. Close (); console. readkey ();  Break  ;}  //  Disable the server  Tcplistener. Stop ();}}} 

The output result of the program is the same as the result of the previous socket implementation, so no textures are made here. The web server implemented here is implemented by setting up the console application, if you are interested, you can also use a Windows form to implement it. At the same time, it simply lists the implementation in synchronous mode. At the same timeTcplistenerClass andTcpclientClasses support asynchronous operations at the same time. The following table lists the methods for asynchronous operations in these two classes:

Class

Method

Description

Tcplistener

Beginaccepttcpclient

Start an asynchronous operation to accept an incoming connection

Endaccepttcpclient

Receives incoming connections asynchronously and creates a new tcpclient object to process client communication.

Tcpclient

Beginconnect

Starts an asynchronous request for remote host connection.

Endconnect

Asynchronously accept incoming connection attempts.

If you want to know the thread synchronous and asynchronous friends can refer to my multithreading processing series: http://www.cnblogs.com/zhili/archive/2012/07/21/ThreadsSynchronous.html

 

Iii. Summary

Here this articleArticleThis topic describes how to customize a simple Web server. Through this topic, we hope you can have a simple understanding of the working process of the Web server.

In this topic, we use the IE browser to send customer requests. Therefore, we will introduce a custom browser to send requests to the Web server through our custom browser, then, display the response message in your custom browser.

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.