Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML using System; using System.Collections.Generic; using System.Text; namespace HTTPServer { class Server { static void Main( string [] args) { } } }
Copy Source | Copy HTML
- class server
- {
- TcpListener Listener; // Object accepting TCP clients
- // Start the server
- public Server ( int Port)
- {
- // Create a "listener" for the specified port
- Listener = new TcpListener (IPAddress.Any, Port);
- Listener.Start (); // Run it
- // In an infinite loop
- while ( true )
- {
- // Accept new customers
- Listener.AcceptTcpClient ();
- }
- }
- // Stop Server
- ~ Server ()
- {
- // If the "listener" was created
- if (Listener! = null )
- {
- // stop it
- Listener.Stop ();
- }
- }
- static void Main ( string [] args)
- {
- // Create a new server on port 80
- new Server ( 80 );
- }
- }
Copy Source | Copy HTML
- // class handler client
- class Client
- {
- // Constructor class. He needs to transfer the received client from TcpListener
- public Client (TcpClient Client )
- {
- // Simple HTML Page Code
- string Html = "<html> <body> <h1> It works! </ h1> </ body> </ html>" ;
- // Required headers: server response, content type and length. After two blank lines - the content itself
- string Str = "HTTP / 1.1 200 OK \ nContent-type: text / html \ nContent-Length:" + Html.Length.ToString () + "\ n \ n" + Html;
- // Let's bring the string to the form of the byte array
- byte [] Buffer = Encoding.ASCII.GetBytes (Str);
- // Send it to the client
- Client .GetStream (). Write ( Buffer , 0 , Buffer .Length);
- // Close the connection
- Client .Close ();
- }
- }
Copy Source | Copy HTML
- // Accept new clients and pass them on to the new instance of the Client class.
- new Client (Listener.AcceptTcpClient ());
Copy Source | Copy HTML
- static void ClientThread ( Object StateInfo)
- {
- new Client ((TcpClient) StateInfo);
- }
Copy Source | Copy HTML
- // Accept new customer
- TcpClient Client = Listener.AcceptTcpClient ();
- // Create a stream
- Thread Thread = new Thread ( new ParameterizedThreadStart (ClientThread));
- // And launch this stream, passing it the received client
- Thread .Start (Client);
Copy Source | Copy HTML
- // Accept new customers. After the client has been accepted, it is transferred to the new thread (ClientThread)
- // using the thread pool.
- ThreadPool.QueueUserWorkItem ( new WaitCallback (ClientThread), Listener.AcceptTcpClient ());
Copy Source | Copy HTML
- // Determine the desired maximum number of threads
- // Let it be 4 per processor
- int MaxThreadsCount = Environment .ProcessorCount * 4 ;
- // Set the maximum number of worker threads
- ThreadPool.SetMaxThreads (MaxThreadsCount, MaxThreadsCount);
- // Set the minimum number of worker threads
- ThreadPool.SetMinThreads ( 2 , 2 );
Copy Source | Copy HTML
- // Declare a line in which the client request will be stored
- string Request = "" ;
- // Buffer for storing data received from the client
- byte [] Buffer = new byte [ 1024 ];
- // Variable to store the number of bytes received from the client
- int Count;
- // Read from the client's stream until data from it is received
- while ((Count = Client.GetStream (). Read ( Buffer , 0 , Buffer .Length))> 0 )
- {
- // Convert this data to a string and add it to the Request variable
- Request + = Encoding.ASCII.GetString ( Buffer , 0 , Count);
- // The request must be terminated by the sequence \ r \ n \ r \ n
- // Either stop receiving the data themselves if the length of the Request string exceeds 4 kilobytes
- // We do not need to receive data from a POST request (and so on), but a regular request
- // in theory should not be more than 4 kilobytes
- if (Request.IndexOf ( "\ r \ n \ r \ n" )> = 0 || Request.Length> 4096 )
- {
- break ;
- }
- }
Copy Source | Copy HTML
- // Parsing the query string using regular expressions
- // At the same time cut off all the variables of the GET request
- Match ReqMatch = Regex . Match (Request, @ "^ \ w + \ s + ([^ \ s \?] +) [^ \ S] * \ s + HTTP /.* |" );
- // If the request failed
- if (ReqMatch == Match .Empty)
- {
- // Pass error 400 to the client - invalid request
- SendError (Client, 400 );
- return ;
- }
- // Get the query string
- string RequestUri = ReqMatch.Groups [ 1 ] .Value;
- // Bring it to its original form, converting escaped characters
- // For example, "% 20" -> ""
- RequestUri = Uri .UnescapeDataString (RequestUri);
- // If the line contains a colon, pass error 400
- // This is needed to protect against URLs like http://example.com/../../file.txt
- if (RequestUri.IndexOf ( ".." )> = 0 )
- {
- SendError (Client, 400 );
- return ;
- }
- // If the query string ends in "/", then add to it index.html
- if (RequestUri.EndsWith ( "/" ))
- {
- RequestUri + = "index.html" ;
- }
Copy Source | Copy HTML
- string FilePath = "www /" + RequestUri;
- // If this file does not exist in the www folder, send a 404 error
- if (! File .Exists (FilePath))
- {
- SendError (Client, 404 );
- return ;
- }
- // Get the file extension from the query string
- string Extension = RequestUri.Substring (RequestUri.LastIndexOf ( '.' ));
- // Content type
- string ContentType = "" ;
- // Trying to determine the content type by file extension
- switch (Extension)
- {
- case ".htm" :
- case ".html" :
- ContentType = "text / html" ;
- break ;
- case ".css" :
- ContentType = "text / stylesheet" ;
- break ;
- case ".js" :
- ContentType = "text / javascript" ;
- break ;
- case ".jpg" :
- ContentType = "image / jpeg" ;
- break ;
- case ".jpeg" :
- case ".png" :
- case ".gif" :
- ContentType = "image /" + Extension.Substring ( 1 );
- break ;
- default :
- if (Extension.Length> 1 )
- {
- ContentType = "application /" + Extension.Substring ( 1 );
- }
- else
- {
- ContentType = "application / unknown" ;
- }
- break ;
- }
- // Open the file, insuring against errors
- FileStream FS;
- try
- {
- FS = new FileStream (FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
- }
- catch ( Exception )
- {
- // If an error occurs, send error 500 to the client
- SendError (Client, 500 );
- return ;
- }
- // Send Headers
- string Headers = "HTTP / 1.1 200 OK \ nContent-Type:" + ContentType + "\ nContent-Length:" + FS.Length + "\ n \ n" ;
- byte [] HeadersBuffer = Encoding.ASCII.GetBytes (Headers);
- Client.GetStream (). Write (HeadersBuffer, 0 , HeadersBuffer.Length);
- // Until the end of the file is reached
- while (FS.Position <FS.Length)
- {
- // Read data from file
- Count = FS.Read ( Buffer , 0 , Buffer .Length);
- // And pass them on to the client.
- Client.GetStream (). Write ( Buffer , 0 , Count);
- }
- // Close The File And Connection
- FS.Close ();
- Client.Close ();
Copy Source | Copy HTML
- // Send the page with an error
- private void SendError ( TcpClient Client, int Code)
- {
- // Get a string like "200 OK"
- // HttpStatusCode stores all HTTP / 1.1 status codes
- string CodeStr = Code.ToString () + "" + ((HttpStatusCode) Code) .ToString ();
- // Simple HTML Page Code
- string Html = "<html> <body> <h1>" + CodeStr + "</ h1> </ body> </ html>" ;
- // Required headers: server response, content type and length. After two blank lines - the content itself
- string Str = "HTTP / 1.1" + CodeStr + "\ nContent-type: text / html \ nContent-Length:" + Html.Length.ToString () + "\ n \ n" + Html;
- // Let's bring the string to the form of the byte array
- byte [] Buffer = Encoding.ASCII.GetBytes (Str);
- // Send it to the client
- Client.GetStream (). Write ( Buffer , 0 , Buffer .Length);
- // Close the connection
- Client.Close ();
- }
Source: https://habr.com/ru/post/120157/
All Articles