Implement web server with C # Builder

zhaozj2021-02-08  276

Xu Changyou

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 the port 808; waiting, accept the client to connect to the port 808; create the input stream associated with the Socket word and Output stream; then read the client's request information, if the request type is get, then get the HTML file name accessed from the request information. If the HTML file exists, open the HTML file, put the HTTP header information 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. 1. The role of the HTTP protocol WWW is an application system with Internet as a transmission medium, 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 role of the HTTP protocol includes 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 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 file name points to the file accessed, and HTTP / 1.0 pointed out 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 has established a connection with www.mycomputer.com:808/mydir/index.html, it will 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 information 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: The length value indicates the length of the HTTP body information (bytes). 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 # Builder implementation of the programming of the web server function According to the principle of the above HTTP protocol, the method of implementing the GET request is as follows: Create a TCPListener class object, listen to a port (any input idle port as: 808, default is 80 Port). Wait, accept the client to connect to the port, get the socket connected to the client; read the request information submitted by a line client from the input stream associated with the socket, requesting the format of the request: 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 the Socket, and then close the file. Otherwise send an error message to the web browser; close the socket word connected to the corresponding web browser. Third, complete the encoding start C # Builder, select Menu File-> New-> Other, there is a console application in C # Projects in the New ITEM window to determine.

In the New Application Name complete code input window WebServer procedures are as follows: namespace webserver {using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading class MyWebServer {private TCPListener MyListener Private INT port = 808 // Web server port, usually 80public mywebserver () {Try {// Start listening port myListener = new TCPListener (port) mylistener.start (); console.writeline ("My Web Server) .0) Running ... "); // Start a monitoring process Thread THREAD TH = New Threadstart (StartListen)); th.start ()} catch (Exception E) {Console.writeline monitor error: " 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: mywebserver / 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) {if ((NumBytes = mysocket.send (bsenddata, bsenddata.length, 0)) == -1) Console.writeline ("

Socket Error Cannot Send Packet "); Else {Console.writeline (" NO. Of Bytes Send {0} ", NumBytes);}} Elseconsole.writeline (" Connection Fail ... ");} catch (Exception E) {Console.WriteLine ("Errors: {0}", E);}} public static void main ()}} public static void main () {MyWebServer mws = new mywebserver ();} public void startlisten () {int tentartpos = 0; string Srequest; string sDirName; String sRequestedFile; String sErrorMessage; String sLocalDir; String sPhysicalFilePath; // virtual directory String sMyWebServerRoot = "C: // Inetpub // wwwroot //"; String sFormattedMessage = ""; String sResponse = ""; while (true) {// Accept new connection socket mySocket = myListener.acceptsocket () console.writeline ("socket type" mysocket.sockettype); if (mysocket.connected) {Console.writeline ("/ N client 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); // Processing "GET" request type if (sBuffer.Substring (0, 3)! = "get") { Console.writeline ("Processes the Get Request Type."); MySocket.cl OSE (); 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 nor "/", "/" ing ((SREQUEST .Indexof (".") <1) && (! SREQUEST.ENDSWITH (")))) {SREQUEST = SREQUEST " / ";} // Goes with request file name iStartPos = SREQUEST.LastIndexof (" / ") 1; SrequestedFile =

SREQUEST.SUBSTRING (ISTARTPOS); // Get request file directory sdirName = Srequest.Substring (Srequest.indexof ("/"), Srequest.LastIndexof ("/") - 3); // Get virtual directory physical path slocaldir = SMYWEBSERROOT Console.writeline ("Request file directory: slocaldir); if (slocaldir.length == 0) {serrorMessage ="

error !! Requested Directory Does not exists
"; Sendheader SHTTPVERSION, "" ", SERRORMESSAGE.LENGTH," 404 Not found ", ref mySocket; SendTobrowser (SERRORMESSAGE, REF MySocket); MySocket.close (); Continue;} if (SrequestedFile.Length == 0) {// acquisition request File name SREQUESTEDFILE = "index.html";} // acquire 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 = "

404 error! file does not exists ... "; Sendheader (SHTTPVERSION, ", SERRORMESSAGE.LENGTH," 404 Not Found ", Ref MySocket; SendTobrowser (SERMESSAGE, REF MySocket); console.writeline;} else {INT I TotBytes = 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 = = reader.read (bytes, 0, bytes.length))! = 0) {SRESPONSE = SRESPONSE Encoding.ascii.getstring (Bytes, 0, Read); ITOTBYTES = ITOTBYTES READ Reader.close (); fs.close (); Sendheader (SHTTPVERSION, SMIMETYPE, ITOTBYTES, 200 OK "

转载请注明原文地址:https://www.9cbs.com/read-2715.html

New Post(0)