Establish your own web server with C #

xiaoxiao2021-03-06  73

Personal collection, only for archiving. Today, the disk is sorted out, no place to put it. Throw blog.

Don't understand, don't ask me.

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; // select 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 TH = 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) {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 ("Effect: {0}" , e);}}}}}} 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 srmattedMessage = ""; string sretonse = "

While (true) {// accepts a new connection 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 the 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 "/";} // deliver the request file name ostartpos = SREQUEST.LastIndexof ("/") 1; SrequestedFile = Srequest.Substring (iStartPOS);

// Get the request file directory sdirName = SREQUEST.SUBSTRING (SREQUEST.INDEXOF ("/"), Srequest.lastIndexof ("/") - 3);

// Get the virtual directory physical path slocaldir = SMYWEBSERVERROOT;

Console.writeline ("Request file directory: slocaldir);

IF (SlocalDir.Length == 0) {serror !! Requested Directory Does Not Existsted Directory Does NOT EXISTS
"; Sendheader (SHTTPVERSION,", "404 Not Found", Ref mysocket; sendtobrowser (sero "; mysocket.close (); continue;}

IF (SREQUESTEDFILE.LENGTH == 0) {// acquisition request file name SREQUESTEDFILE = "index.html";

/// get 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 = "

404 error! file does not exists ... "; Sendheader (SHTTPVERSION, "," 404 not found ", ref mySocket; SendTobrowser (SERMESSAGE, REF MYSOCKET) ;

Console.writeline (srmattedMessage);

Else {Int itotbytes = 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 = 0) {SRES.LENGTH)! = 0) {sResponse = SRESPONSE Encoding.ascii.getstring (bytes, 0, read); itotbytes = itotbytes 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 ();}}}

}

}

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

New Post(0)