This is just a simple WEB server written by c #, only the GET method's request for HTML files, interested friends can continue to develop more functions on this basis, F10/6, leak, hope Please see cool! !
Summary:
WWW's work is based on client / server computing model, consisting of a web browser (client) and web server (server), and the HTTP protocol is used by HTTP protocols, including four Steps: Connection, request, answer. According to the principle of the above HTTP protocol, this paper implements the method of the GET request, by creating the TCPListener class object, listening to port 8080; waiting, accept client connection to port 8080; create input streams associated with the socket word and Output stream; then read the client's request information, if the request type is get, then obtain the HTML file name accessed in the request information. If the HTML file exists, open the HTML file, put the HTTP header æ and HTML file content Pass back to the web browser via Socket and close the file. Otherwise send an error message to the web browser. Finally, close the Socket word connected to the corresponding web browser.
First, the principle of the role of the HTTP protocol
WWW is an application system as a transmission medium in an Internet, and the most basic transmission unit on the WWW online is a web page. WWW's work is based on client / server computing models, composed of a web browser (client) and web server (server), and the hypertext transfer protocol (HTTP) is communicated between the two. The HTTP protocol is based on protocols above the TCP / IP protocol, which is an application layer protocol between web browses and web servers, which is a general, stateless, object-oriented protocol. The principle of the role of the HTTP protocol consists of four steps:
Connection: The web browser establishes a connection to the web server, open a virtual file called Socket (socket), and the establishment of this file flag is successful.
Request: The web browser submits a request to the web server via Socket. The request of HTTP is generally the GET or POST command (POST is used for the transfer of the FORM parameter). The format of the GET command is:
Get path / file name HTTP / 1.0
The file name indicates the files accessed, and HTTP / 1.0 pointers the HTTP version used by the web browser.
Available: After the web browser submits the request, transfer to the web server via the HTTP protocol. After the web server is connected, transaction processing, the processing result is sent back to the web browser via HTTP, so that the requested page is displayed on the web browser.
Example: Assume that the client is established with www.mycomputer.com:8080/mydir/index.html, send the get command: get /mydir/index.html http / 1.0. The host named www.mycomputer.com's web server search subdirectory MyDir file index.html from its documentation space. If you find this file, the web server transmits the content to the corresponding web browser.
In order to inform the web browser, the web server first transmits some HTTP header information, then transmits the specific content (ie HTTP body information), and HTTP header information and HTTP body information are separated from one space.
Common HTTP headers are:
1 http 1.0 200 ok
This is the first line of the web server response, lists the HTTP version number and response code that the server is running. The code "200 ok" indicates the completion of the request. 2 MIME_VERSION: 1.0
It indicates the version of the MIME type.
3 Content_Type: Type
This header is very important, it indicates the MIME type of HTTP information. Such as: content_type: text / html indicates that the transferred data is an HTML document.
4 Content_length: length value
It indicates the length (bytes) of HTTP information.
Close connection: When the response is completed, the web browser must disconnect to ensure that other web browsers can connect with the web server.
Second, C # Program Design of Web Server Function
According to the principles of the above HTTP protocol, the method of implementing the web server program for GET request is as follows:
Create a TCPListener class object to monitor a port (any input idle ports such as: 8080).
Wait, accept the client to connect to this port to get the socket connected to the client;
Read the request information submitted by a line client from the input stream associated with the socket, the request information is: GET path / file name HTTP / 1.0
Get the request type from the request information. If the request type is GET, get the HTML file name accessed from the request information. When there is no HTML file name, use index.html as a file name;
If the HTML file exists, open the HTML file, transfer the HTTP header information and the HTML file content to the web browser via Socket, then close the file. Otherwise send an error message to a web browser;
Close the socket word connected to the corresponding web browser.
The code implemented is as follows: //webserver.cs//
Namespace cnnbsun.webserver {using system; using system.io; using system.net.sockets; using system.text; using system.Text;
Class mywebserver {
Private TCPListener MyListener; Private INT port = 8080; // Waiter Any idle port
// Start a listening port // Start a listed process public mywebserver () {{// Start and listening port myListener = new TCPListener (port); MYListener.start (); console.writeline ("Web Server Running. .. Press ^ c to stop ... "); // Start a listening process 'StartListen' Thread THREAD THREAD (New ThreadStart (StartListen)); th.Start ();
} Catch (Exception e) {Console.WriteLine ( "Error while concurrently listening port:" e.ToString ());}} public void SendHeader (string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket) {
String sbuffer = ""; if (smimeHeader.Length == 0) {smimeHeader = "text / html"; // default text / html} SBuffer = SBuffer Shttpversion SSTATUSCODE "/ R / N"; SBuffer = SBuffer "Server: CX1193719-B / R / N"; SBuffer = SBuffer "Content-Type:" SmimeHeader "/ R / N"; SBuffer = SBuffer "Accept-Ranges: BYTES / R / N"; SBuffer = SBuffer "Content-Length:" ITOTBYTES "/ R / N / R / N"; Byte [] bsenddata = encoding.ascii.getbytes (sbuffer);
SendTobrowser (BSENDDATA, REF MySocket);
Console.writeline ("Total Bytes:" ITOTBYTES.TOSTRING ());
}
Public void sendtobrowser (STRING SDATA, REF Socket MySocket) {SendTobrowser (ENCODING.ASCII.GetBytes (SDATA), Ref MySocket
Public void sendtobrowser (byte [] bsenddata, ref socket mysocket) {int numBytes = 0; try {if (mysocket.connected) {ix ((NumBytes = mysocket.send (bsenddata, bsenddata.length) == -1 ) Console.writeline ("socket error cannot send packet); Else â {Console.writeline (" no. Of bytes send {0} ", numbertes);}} else console.writeline (" Connection failed ... ") (Exception E) {Console.writeline ("Errors: {0}", E);}} public static void main ()}} public static void main ()}} public static void main () {MyWebServer Mws = new mywebserver ();} public void startlisten ()}
int iStartPos = 0; String sRequest; String sDirName; String sRequestedFile; String sErrorMessage; String sLocalDir; / Note Set your own virtual directory / String sMyWebServerRoot = "E: // MyWebServerRoot //"; // set up your virtual directory // String sPhysicalFilePath = ""; String sFormattedMessage = ""; String sResponse = ""; while (true) {// accept new connections Socket mySocket = myListener.AcceptSocket (); Console.WriteLine ( "Socket Type" mySocket. Sockettype); if (mysocket.connected) {console.writeline ("/ nclient connection !! / n =========================== / nclient ip {0} / n", MySocket.RemoteEndPoint;
Byte [] BRECEIVE = New byte [1024]; Int i = mysocket.receive (Breceive, Breceive.length, 0);
// Convert to string type string sbuffer = encoding.ascii.getstring (BRECEIVE);
// Process "GET" request type if (sbuffer.substring (0, 3)! = "Get") {console.writeline ("only processes the GET request type."); Mysocket.close (); Return;}
/ / Find "http" location iStartPos = SBuffer.indexof ("http", 1);
String Shttpversion = SBuffer.Substring (iStartPos, 8); // Get request type and file directory file name SREQUEST = SBuffer.substring (0, iStartPOS - 1); Srequest.Replace ("//", "/");
// If the end is not the file name, it is not "/" if it ends "/" if ("(Srequest.indexof (") <1) && (! Srequest.EndSwith ("))) {SREQUEST = SREQUEST "/";
// Get a request file name iStartPos = SREQUEST.LastIndexof ("/") 1; SrequestedFile = Srequest.substring (iStartPOS);
// Get the request file directory sdirName = SREQUEST.SUBSTRING (SREQUEST.INDEXOF ("/"), Srequest.lastIndexof ("/") - 3); // Get virtual directory physical path slocaldir = SMYWEBSERVERROOT; console.writeLine ("request Document Directory: " SLOCALDIR);
IF (SlocalDir.Length == 0) {serror !! Requested Directory Does Not Existsted Directory Does NOT EXISTS H2>
"; Sendheader (SHTTPVERSION,", "404 Not Found", Ref mysocket; sendtobrowser (sero "; mysocket.close (); continue;}
IF (SREQUESTEDFILE.LENGTH == 0) {// acquisition request file name SREQUESTEDFILE = "index.html";
/ / / Over the request file type (set to text / html) / string smimetype = "text / html";
sPhysicalFilePath = sLocalDir sRequestedFile; Console.WriteLine ( "request file:" sPhysicalFilePath); if (File.Exists (sPhysicalFilePath) == false) {sErrorMessage = "
Console.writeline;} else {int ketbytes = 0;
SRESPONSE = ""
FileStream fs = new FileStream (sPhysicalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader reader = new BinaryReader (fs); byte [] bytes = new byte [fs.Length]; int read; while ((read = Reader.Read (Bytes, 0, Bytes.length))! = 0) {SRESPONSE = SRESPONSE Encoding.ascii.getstring (bytes, 0, read); itotbytes = ketbytes read;
} Reader.close (); fs.close ();
Sendheader (SHTTPVERSION, SMIMETYPE, ITOTBYTES, "200 OK", Ref MySocket; SendTobrowSer (Bytes, Ref MySocket); //mysocket.send (Bytes, Bytes.length, 0);
} Mysocket.close ();}}}
}
}
///end
Compiling files into an EXE file, you have implemented simple web server features! You can set a virtual directory for testing!